Skip to main content

测试自动化

有关编写单元测试的特定于文件的说明。

注意

  • 此库中的示例旨在提供灵感,建议进行相应调整,使其更特定于你的项目、语言和团队流程。
  • 如需获取社区提供的有关特定语言和场景的自定义指令示例,请参阅出色的 GitHub Copilot 自定义内容仓库。
  • 可以跨不同范围应用自定义指令,具体取决于要在其中创建自定义指令的平台或 IDE。 有关详细信息,请参阅“关于自定义 GitHub Copilot 聊天助手响应”。

此示例使用 applyTo 字段显示了特定于路径的 python-tests.instructions.md 文件,该文件仅适用于仓库中的 Python 测试文件。 有关特定于路径的说明文件的详细信息,请参阅 为 GitHub Copilot 添加存储库自定义说明

Text
---
applyTo: "tests/**/*.py"
---

When writing Python tests:

## Test Structure Essentials
- Use pytest as the primary testing framework
- Follow AAA pattern: Arrange, Act, Assert
- Write descriptive test names that explain the behavior being tested
- Keep tests focused on one specific behavior

## Key Testing Practices
- Use pytest fixtures for setup and teardown
- Mock external dependencies (databases, APIs, file operations)
- Use parameterized tests for testing multiple similar scenarios
- Test edge cases and error conditions, not just happy paths

## Example Test Pattern
```python
import pytest
from unittest.mock import Mock, patch

class TestUserService:
    @pytest.fixture
    def user_service(self):
        return UserService()
    
    @pytest.mark.parametrize("invalid_email", ["", "invalid", "@test.com"])
    def test_should_reject_invalid_emails(self, user_service, invalid_email):
        with pytest.raises(ValueError, match="Invalid email"):
            user_service.create_user({"email": invalid_email})
    
    @patch('src.user_service.email_validator')
    def test_should_handle_validation_failure(self, mock_validator, user_service):
        mock_validator.validate.side_effect = ConnectionError()
        
        with pytest.raises(ConnectionError):
            user_service.create_user({"email": "[email protected]"})
```