dissolve-python 0.3.0

A tool to dissolve deprecated calls in Python codebases
Documentation
"""
Integration tests using deprecated library functions.

This module shows how deprecated functions might be used in test code,
which also needs to be migrated.
"""

import sys
import os
import unittest
import asyncio

# Add the library to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from library.utils import old_add, old_multiply, square, cube, legacy_divide
from library.models import OldDataProcessor, LegacyUser, SimpleProcessor
from library.async_ops import old_fetch_data, legacy_upload
from library.processors import ProcessingEngine, DataValidator
from library.containers import LegacyContainer, SmartList


class TestDeprecatedFunctions(unittest.TestCase):
    """
    Test cases using deprecated functions.
    
    These tests will need to be updated when deprecated functions
    are removed from the library.
    """
    
    def test_deprecated_math_functions(self):
        """Test deprecated mathematical functions."""
        # Test old_add
        result = old_add(5, 3)
        self.assertEqual(result, 8)
        
        # Test old_multiply
        result = old_multiply(4, 6)
        self.assertEqual(result, 24)
        
        # Test square function
        result = square(7)
        self.assertEqual(result, 49)
        
        # Test cube function
        result = cube(4)
        self.assertEqual(result, 64)
        
        # Test legacy_divide
        result = legacy_divide(15, 3)
        self.assertEqual(result, 5.0)
    
    def test_deprecated_processor_class(self):
        """Test deprecated data processor class."""
        processor = OldDataProcessor("test_db", cache_size=10)
        
        # Test processing
        result = processor.process("test_data")
        self.assertIn("test_data", result)
        self.assertIn("batch_size=20", result)  # cache_size * 2
        
        # Test getting info
        info = processor.get_info()
        self.assertEqual(info["data_source"], "test_db")
        self.assertEqual(info["batch_size"], 20)
    
    def test_legacy_user_methods(self):
        """Test deprecated user methods."""
        user = LegacyUser("test_user", "test@example.com", active=True)
        
        # Test deprecated get_name method
        name = user.get_name()
        self.assertEqual(name, "test_user")
        
        # Test deprecated set_profile_data method
        profile = user.set_profile_data({"age": 25, "city": "NYC"})
        self.assertEqual(profile["age"], 25)
        self.assertEqual(profile["city"], "NYC")
        
        # Test deprecated property
        enabled = user.is_enabled
        self.assertTrue(enabled)
    
    def test_simple_processor(self):
        """Test deprecated simple processor."""
        processor = SimpleProcessor("test_source")
        result = processor.process_item("test_item")
        
        self.assertIn("test_item", result)
        self.assertIn("test_source", result)
    
    def test_deprecated_static_methods(self):
        """Test deprecated static methods."""
        # Test deprecated validation
        is_valid = ProcessingEngine.old_validate_data(["test", "data"])
        self.assertTrue(is_valid)
        
        # Test deprecated text cleaning
        cleaned = ProcessingEngine.legacy_clean_text("  HELLO WORLD  ")
        self.assertEqual(cleaned, "hello world")
        
        # Test deprecated batch processing
        result = ProcessingEngine.old_process_batch(
            ["Item1", "Item2"], 
            uppercase=False, 
            trim=True
        )
        self.assertEqual(result, ["item1", "item2"])
    
    def test_deprecated_class_methods(self):
        """Test deprecated class methods."""
        # Test old engine creation
        engine = ProcessingEngine.old_create_engine(fast=True)
        self.assertEqual(engine.engine_type, "fast")
        
        engine = ProcessingEngine.old_create_engine(fast=False)
        self.assertEqual(engine.engine_type, "memory_efficient")
        
        # Test legacy fast processor
        fast_engine = ProcessingEngine.legacy_fast_processor()
        self.assertEqual(fast_engine.engine_type, "fast")
    
    def test_deprecated_validators(self):
        """Test deprecated validator methods."""
        # Test email validation
        valid = DataValidator.check_email("test@example.com")
        self.assertTrue(valid)
        
        invalid = DataValidator.check_email("invalid_email")
        self.assertFalse(invalid)
        
        # Test phone validation
        valid_phone = DataValidator.validate_phone_number("555-123-4567")
        self.assertTrue(valid_phone)
        
        # Test strict validator creation
        validator = DataValidator.create_strict_validator()
        self.assertTrue(validator.strict_mode)
    
    def test_deprecated_container_methods(self):
        """Test deprecated container methods."""
        container = LegacyContainer(["a", "b", "c"])
        
        # Test deprecated size method
        size = container.size()
        self.assertEqual(size, 3)
        
        # Test deprecated string conversion
        string_rep = container.to_str()
        self.assertIn("3 items", string_rep)
        
        # Test deprecated item access
        item = container.get_item(0)
        self.assertEqual(item, "a")
        
        # Test deprecated item setting
        container.set_item(1, "modified")
        self.assertEqual(container._items[1], "modified")
        
        # Test deprecated contains method
        contains = container.contains("a")
        self.assertTrue(contains)
    
    def test_smart_list_deprecated_methods(self):
        """Test deprecated SmartList methods."""
        smart_list = SmartList([1, 2, 3])
        
        # Test deprecated length methods
        length = smart_list.length()
        self.assertEqual(length, 3)
        
        count = smart_list.get_count()
        self.assertEqual(count, 3)
        
        # Test deprecated empty check
        empty = smart_list.is_empty()
        self.assertFalse(empty)
        
        empty_list = SmartList([])
        empty_check = empty_list.is_empty()
        self.assertTrue(empty_check)
        
        # Test deprecated has_item method
        has_item = smart_list.has_item(2)
        self.assertTrue(has_item)
        
        no_item = smart_list.has_item(99)
        self.assertFalse(no_item)


class TestDeprecatedAsync(unittest.IsolatedAsyncioTestCase):
    """
    Async test cases using deprecated async functions.
    """
    
    async def test_old_fetch_data(self):
        """Test deprecated fetch data function."""
        result = await old_fetch_data("https://test.example.com")
        
        self.assertEqual(result["url"], "https://test.example.com")
        self.assertEqual(result["timeout"], 30)
        self.assertEqual(result["status"], 200)
    
    async def test_legacy_upload(self):
        """Test deprecated upload function."""
        result = await legacy_upload("test.txt", "https://upload.example.com")
        
        self.assertEqual(result["file_path"], "test.txt")
        self.assertEqual(result["destination"], "https://upload.example.com")
        self.assertEqual(result["chunk_size"], 4096)
        self.assertEqual(result["status"], "uploaded")


class TestMigrationScenarios(unittest.TestCase):
    """
    Test scenarios that demonstrate typical migration cases.
    """
    
    def test_nested_deprecated_calls(self):
        """Test nested calls to deprecated functions."""
        # Nested deprecated function calls
        inner_result = old_add(5, 3)
        outer_result = old_multiply(inner_result, 2)
        final_result = square(outer_result)
        
        # This should equal (5+3) * 2 squared = 16^2 = 256
        self.assertEqual(final_result, 256)
    
    def test_deprecated_in_comprehensions(self):
        """Test deprecated functions used in list comprehensions."""
        numbers = [1, 2, 3, 4, 5]
        
        # Using deprecated functions in comprehensions
        squares = [square(n) for n in numbers]
        self.assertEqual(squares, [1, 4, 9, 16, 25])
        
        cubes = [cube(n) for n in numbers if n > 2]
        self.assertEqual(cubes, [27, 64, 125])
    
    def test_deprecated_in_lambda(self):
        """Test deprecated functions in lambda expressions."""
        numbers = [1, 2, 3, 4, 5]
        
        # Using deprecated functions in lambda
        add_ten = lambda x: old_add(x, 10)
        results = list(map(add_ten, numbers))
        self.assertEqual(results, [11, 12, 13, 14, 15])
        
        # Using deprecated functions in filter
        even_squares = list(filter(lambda x: square(x) % 2 == 0, numbers))
        # Only even numbers have even squares: 2, 4
        self.assertEqual(even_squares, [2, 4])
    
    def test_deprecated_with_error_handling(self):
        """Test deprecated functions with error handling."""
        try:
            # This should work fine
            result = legacy_divide(10, 2)
            self.assertEqual(result, 5.0)
        except Exception as e:
            self.fail(f"Unexpected exception: {e}")
        
        # Test division by zero
        with self.assertRaises(ValueError):
            legacy_divide(10, 0)
    
    def test_mixed_old_and_new_apis(self):
        """Test mixing deprecated and new API calls."""
        # This simulates code that's partially migrated
        from library.utils import add, multiply  # New APIs
        
        # Mix of old and new function calls
        old_result = old_add(5, 3)     # Deprecated
        new_result = add(7, 2)         # New API
        combined = multiply(old_result, new_result)  # New API with old input
        
        # Should be (5+3) * (7+2) = 8 * 9 = 72
        self.assertEqual(combined, 72)


def run_tests():
    """Run all tests with proper output."""
    print("=== Running Integration Tests with Deprecated Functions ===")
    print("Note: You will see deprecation warnings during test execution.")
    print("This is expected and demonstrates the library's warning system.\n")
    
    # Create test suite
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    
    # Add test cases
    suite.addTests(loader.loadTestsFromTestCase(TestDeprecatedFunctions))
    suite.addTests(loader.loadTestsFromTestCase(TestDeprecatedAsync))
    suite.addTests(loader.loadTestsFromTestCase(TestMigrationScenarios))
    
    # Run tests
    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)
    
    print(f"\n=== Test Results ===")
    print(f"Tests run: {result.testsRun}")
    print(f"Failures: {len(result.failures)}")
    print(f"Errors: {len(result.errors)}")
    
    if result.failures:
        print(f"\nFailures:")
        for test, traceback in result.failures:
            print(f"  {test}: {traceback}")
    
    if result.errors:
        print(f"\nErrors:")
        for test, traceback in result.errors:
            print(f"  {test}: {traceback}")
    
    print(f"\n=== Migration Instructions ===")
    print("To migrate this test file:")
    print("  dissolve migrate consumer/test_integration.py")
    print("To apply migrations:")
    print("  dissolve migrate --write consumer/test_integration.py")
    
    return result.wasSuccessful()


if __name__ == "__main__":
    success = run_tests()
    sys.exit(0 if success else 1)