Files
cleveragents-core/tests/unit/conftest.py

127 lines
3.3 KiB
Python

"""
Pytest configuration and fixtures for unit tests
Provides cleanup for temporary files created during tests.
"""
import pytest
import os
import tempfile
from pathlib import Path
@pytest.fixture
def temp_yaml_file():
"""Create a temporary YAML file and clean it up after the test."""
temp_file = tempfile.NamedTemporaryFile(
mode='w', prefix='cleveragent_', suffix='.yaml', delete=False
)
temp_file.close()
yield temp_file.name
# Cleanup
try:
os.unlink(temp_file.name)
except (FileNotFoundError, PermissionError):
pass
@pytest.fixture
def temp_json_file():
"""Create a temporary JSON file and clean it up after the test."""
temp_file = tempfile.NamedTemporaryFile(
mode='w', prefix='cleveragent_', suffix='.json', delete=False
)
temp_file.close()
yield temp_file.name
# Cleanup
try:
os.unlink(temp_file.name)
except (FileNotFoundError, PermissionError):
pass
@pytest.fixture
def temp_file_tracker():
"""
Track temporary files created during a test and clean them up.
Usage:
def test_something(temp_file_tracker):
temp_file = temp_file_tracker.create('.yaml')
# ... use temp_file ...
# Automatic cleanup after test
"""
class TempFileTracker:
def __init__(self):
self.files = []
def create(self, suffix='', mode='w', **kwargs):
"""Create a tracked temporary file."""
temp_file = tempfile.NamedTemporaryFile(
mode=mode,
prefix='cleveragent_',
suffix=suffix,
delete=False,
**kwargs
)
temp_file.close()
self.files.append(temp_file.name)
return temp_file.name
def cleanup(self):
"""Clean up all tracked files."""
for filepath in self.files:
try:
os.unlink(filepath)
except (FileNotFoundError, PermissionError):
pass
self.files = []
tracker = TempFileTracker()
yield tracker
tracker.cleanup()
@pytest.fixture(scope="session", autouse=True)
def cleanup_cleveragent_temp_files():
"""
Auto-cleanup fixture that runs after entire test session.
Cleans up CleverAgents-specific temporary files to prevent resource leaks.
Uses 'cleveragent_' prefix to avoid deleting other programs' files.
This is a safety net for any tests that don't use the temp_file_tracker fixture.
"""
yield # Tests run
# After all tests complete, clean up temp files with our prefix
import glob
# Only match files with our specific prefix
patterns = [
"/tmp/cleveragent_*.yaml",
"/tmp/cleveragent_*.json",
"/tmp/cleveragent_*.txt",
"/tmp/cleveragent_*.j2",
"/var/tmp/cleveragent_*.yaml",
"/var/tmp/cleveragent_*.json"
]
cleaned = 0
for pattern in patterns:
for temp_file in glob.glob(pattern):
try:
if os.path.exists(temp_file):
os.unlink(temp_file)
cleaned += 1
except Exception:
pass # Ignore cleanup errors
if cleaned > 0:
print(f"\n✅ Cleaned up {cleaned} CleverAgents temporary test files")