"""
测试模块
提供完整的测试用例覆盖所有功能模块
"""
import os
import sys
from pathlib import Path
# 添加源码路径
src_path = Path(__file__).parent.parent / "src"
sys.path.insert(0, str(src_path))
# 测试配置
TEST_DATA_DIR = Path(__file__).parent / "test_data"
TEST_TEMP_DIR = Path(__file__).parent / "temp"
# 确保测试目录存在
TEST_DATA_DIR.mkdir(exist_ok=True)
TEST_TEMP_DIR.mkdir(exist_ok=True)
# 测试环境配置
TEST_CONFIG = {
"test_project_dir": TEST_DATA_DIR / "test_project",
"test_output_dir": TEST_TEMP_DIR / "output",
"test_cache_dir": TEST_TEMP_DIR / "cache",
"test_config_file": TEST_DATA_DIR / "test_config.yaml"
}
# 通用测试工具
def create_test_project():
"""创建测试项目结构"""
project_dir = TEST_CONFIG["test_project_dir"]
# 清理现有目录
if project_dir.exists():
import shutil
shutil.rmtree(project_dir)
# 创建目录结构
dirs = [
"src",
"src/utils",
"src/services",
"tests",
"docs",
"config",
"scripts"
]
for dir_path in dirs:
(project_dir / dir_path).mkdir(parents=True, exist_ok=True)
# 创建文件
files = [
("README.md", "# Test Project\n\nThis is a test project."),
("src/main.py", "# Main module\n\ndef main():\n pass"),
("src/utils/helpers.py", "# Helper functions\n\ndef helper():\n pass"),
("src/services/api.py", "# API service\n\nclass APIService:\n pass"),
("tests/test_main.py", "# Test main module\n\ndef test_main():\n pass"),
("docs/guide.md", "# User Guide\n\nDocumentation here."),
("config/settings.yaml", "# Configuration\napp:\n name: test"),
("scripts/setup.sh", "# Setup script\n\necho 'Setting up'")
]
for file_path, content in files:
(project_dir / file_path).write_text(content)
return project_dir
def cleanup_test_temp():
"""清理测试临时文件"""
import shutil
for temp_dir in [TEST_CONFIG["test_output_dir"], TEST_CONFIG["test_cache_dir"]]:
if temp_dir.exists():
shutil.rmtree(temp_dir)
# 测试夹具
import pytest
@pytest.fixture(scope="session")
def test_project():
"""测试项目夹具"""
project_dir = create_test_project()
yield project_dir
cleanup_test_temp()
@pytest.fixture
def temp_dir():
"""临时目录夹具"""
import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
yield Path(temp_dir)
@pytest.fixture
def sample_text():
"""示例文本夹具"""
return "This is a sample text for testing purposes."
@pytest.fixture
def sample_config():
"""示例配置夹具"""
return {
"output_dir": "docs",
"template_dir": "templates",
"cache_enabled": True,
"log_level": "INFO"
}