"""Test directory creation and error handling improvements""" import tempfile import shutil import os from pathlib import Path import pytest from src.connector import Config class TestDirectoryCreation: """Test cases for improved directory creation functionality""" def setup_method(self): """Set up test environment""" # Create temporary directory for testing self.temp_base = Path(tempfile.mkdtemp(prefix="gptedit_test_")) # Override environment variables for testing os.environ['GENERATED_IMAGES_PATH'] = str(self.temp_base / 'generated_test') os.environ['TEMP_PATH'] = str(self.temp_base / 'temp_test') os.environ['OPENAI_API_KEY'] = 'sk-test-key-for-testing' # Required for validation def teardown_method(self): """Clean up test environment""" # Clean up temporary directory if self.temp_base.exists(): shutil.rmtree(self.temp_base) # Clean up environment variables for key in ['GENERATED_IMAGES_PATH', 'TEMP_PATH', 'OPENAI_API_KEY']: if key in os.environ: del os.environ[key] def test_basic_directory_creation(self): """Test that directories are created successfully""" config = Config() # Check that both directories exist assert config.generated_images_path.exists() assert config.generated_images_path.is_dir() assert config.temp_path.exists() assert config.temp_path.is_dir() def test_nested_directory_creation(self): """Test creation of nested directories""" # Set nested paths nested_generated = self.temp_base / 'deeply' / 'nested' / 'generated' nested_temp = self.temp_base / 'deeply' / 'nested' / 'temp' os.environ['GENERATED_IMAGES_PATH'] = str(nested_generated) os.environ['TEMP_PATH'] = str(nested_temp) config = Config() # Check that nested directories were created assert config.generated_images_path.exists() assert config.temp_path.exists() assert nested_generated.exists() assert nested_temp.exists() def test_ensure_temp_directory_runtime(self): """Test runtime temp directory recreation""" config = Config() # Delete temp directory shutil.rmtree(config.temp_path) assert not config.temp_path.exists() # Ensure temp directory should recreate it config.ensure_temp_directory() assert config.temp_path.exists() assert config.temp_path.is_dir() def test_ensure_output_directory_runtime(self): """Test runtime output directory recreation""" config = Config() # Delete output directory shutil.rmtree(config.generated_images_path) assert not config.generated_images_path.exists() # Ensure output directory should recreate it config.ensure_output_directory() assert config.generated_images_path.exists() assert config.generated_images_path.is_dir() def test_directory_permissions(self): """Test write permissions in created directories""" config = Config() # Test temp directory write permission test_temp_file = config.temp_path / 'test_write.txt' test_temp_file.write_text('test') assert test_temp_file.exists() test_temp_file.unlink() # Test generated_images directory write permission test_output_file = config.generated_images_path / 'test_write.txt' test_output_file.write_text('test') assert test_output_file.exists() test_output_file.unlink() def test_get_output_path_ensures_directory(self): """Test that get_output_path creates directory if missing""" config = Config() # Delete output directory shutil.rmtree(config.generated_images_path) assert not config.generated_images_path.exists() # get_output_path should recreate the directory output_path = config.get_output_path("test_base", 1, "png") assert config.generated_images_path.exists() assert output_path.parent == config.generated_images_path def test_invalid_directory_path_handling(self): """Test handling of invalid directory paths""" # Try to create directories in a location that doesn't exist and can't be created # This test might need to be adapted based on OS permissions # Set an invalid path (on most systems, you can't create directories in root without permissions) if os.name == 'nt': # Windows invalid_path = 'C:\\invalid_system_path\\gptedit_test' else: # Unix-like invalid_path = '/root/invalid_system_path/gptedit_test' os.environ['GENERATED_IMAGES_PATH'] = invalid_path # This should raise an exception during initialization with pytest.raises(RuntimeError): Config() def test_directory_already_exists(self): """Test that existing directories are handled correctly""" # Create directories manually first generated_path = self.temp_base / 'pre_existing_generated' temp_path = self.temp_base / 'pre_existing_temp' generated_path.mkdir(parents=True) temp_path.mkdir(parents=True) # Add some files to verify they're preserved (generated_path / 'existing_file.txt').write_text('preserved') (temp_path / 'existing_temp.txt').write_text('preserved') # Set environment to use existing directories os.environ['GENERATED_IMAGES_PATH'] = str(generated_path) os.environ['TEMP_PATH'] = str(temp_path) config = Config() # Verify directories still exist and files are preserved assert config.generated_images_path.exists() assert config.temp_path.exists() assert (generated_path / 'existing_file.txt').exists() assert (temp_path / 'existing_temp.txt').exists() if __name__ == "__main__": # Run tests import sys import subprocess # Run with pytest if available try: subprocess.run([sys.executable, '-m', 'pytest', __file__, '-v'], check=True) except (subprocess.CalledProcessError, FileNotFoundError): # Fallback to basic test runner print("Running basic tests...") test_instance = TestDirectoryCreation() test_methods = [method for method in dir(test_instance) if method.startswith('test_')] for method_name in test_methods: print(f"Running {method_name}...") try: test_instance.setup_method() method = getattr(test_instance, method_name) method() test_instance.teardown_method() print(f"✅ {method_name} passed") except Exception as e: print(f"❌ {method_name} failed: {e}") test_instance.teardown_method() print("Basic tests completed!")