Skip to content

Latest commit

 

History

History
513 lines (398 loc) · 11.2 KB

File metadata and controls

513 lines (398 loc) · 11.2 KB

IPython Integration Test

1 Basic IPython Functionality Tests

These tests will verify that IPython is working correctly within Org mode.

!pip install ipython

1.1 Environment Check

First, let’s check our Python environment and ensure IPython is available:

import sys
print(f"Python version: {sys.version}")

# Check if IPython is available
try:
    import IPython
    print(f"IPython version: {IPython.__version__}")
    print(f"IPython is correctly loaded: {'IPython' in sys.modules}")
    
    # Get the current IPython instance
    ipython = IPython.get_ipython()
    if ipython:
        print(f"Active IPython type: {type(ipython).__name__}")
    else:
        print("No active IPython instance found.")
except ImportError:
    print("IPython is not installed in this environment.")

1.2 Session Persistence Test

Let’s define a variable and verify it persists between code blocks:

test_variable = "This variable should persist between code blocks"
print(f"Defined: {test_variable}")

Now let’s check if the variable is still accessible:

try:
    print(f"Retrieved: {test_variable}")
except NameError:
    print("ERROR: The variable was not persisted between code blocks!")

1.3 IPython Magic Commands

Test that IPython magic commands work:

1.3.1 System commands

!echo "Running a system command"

1.3.2 Python environment info

%pylab --no-import-all
%config InlineBackend.figure_format = 'svg'

1.3.3 Time execution

%time sum(range(1000000))

1.3.4 List available magic commands

print("\nAvailable magic commands:")
%lsmagic

1.4 Code Completion and Help

Test help and documentation features:

# This block doesn't require you to press tab, but verifies
# that IPython's rich help is working
help(str.split)

# Print docstring
print("\nDocstring for max function:")
print(max.__doc__)

2 Advanced IPython Features

2.1 Debugging Integration

Test debugger integration:

def function_to_debug(n):
    """A function with steps we can debug"""
    result = 0
    for i in range(n):
        result += i * i
    
    # Uncomment to debug interactively
    # import pdb; pdb.set_trace()
    
    return result

# Run the function without debugging
result = function_to_debug(5)
print(f"Result: {result}")

# How to use the debugger
print("\nTo debug: uncomment the pdb line and re-run")
print("Common pdb commands:")
print("  n - next line")
print("  s - step into function")
print("  c - continue execution")
print("  p <expr> - print expression")
print("  q - quit debugging")

2.2 Error Handling and Traceback

Test error traceback formatting:

try:
    # This will cause an error
    1/0
except Exception as e:
    print(f"Caught exception: {type(e).__name__}: {e}")
    
    # Print traceback
    import traceback
    print("\nTraceback:")
    traceback.print_exc()

2.3 Interactive Plotting

Test matplotlib integration:

import matplotlib.pyplot as plt
import numpy as np

# Create a simple plot
x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.figure(figsize=(8, 4))
plt.plot(x, y, label='sin(x)')
plt.title('Test Plot')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(True)

# Save the figure to view it in Org mode
plt.savefig('test_plot.png')
print("Plot saved to test_plot.png")

2.4 Poetry Environment Integration

Test Poetry environment integration:

# Try to import poetry
try:
    import poetry
    print(f"Poetry is available: {poetry.__version__}")
except ImportError:
    print("Poetry module not directly importable (this is normal)")
    
# Check if we're in a virtual environment
import os
print(f"Using virtual environment: {'VIRTUAL_ENV' in os.environ}")
if 'VIRTUAL_ENV' in os.environ:
    print(f"Virtual env path: {os.environ['VIRTUAL_ENV']}")
    
# List installed packages
print("\nInstalled packages:")
!pip list | grep -E "ipython|numpy|matplotlib"

3 Performance Tests

3.1 Memory Usage

Check memory usage:

# Try using memory_profiler if available
try:
    import memory_profiler
    print("Memory profiler available")
    
    # Define a function to profile
    @memory_profiler.profile
    def memory_test():
        """Test memory usage"""
        # Create a large list
        large_list = [i for i in range(1000000)]
        return sum(large_list)
    
    # Run the function
    result = memory_test()
    print(f"Result: {result}")
    
except ImportError:
    print("Memory profiler not available, install with: pip install memory_profiler")
    
    # Alternative memory usage check
    import resource
    usage = resource.getrusage(resource.RUSAGE_SELF)
    print(f"Memory usage: {usage.ru_maxrss / 1024:.2f} MB")

3.2 Execution Time

Test timing functions:

import time

# Define a function to time
def time_test(n):
    """Test function for timing"""
    start = time.time()
    result = sum(i * i for i in range(n))
    end = time.time()
    return result, end - start

# Run with different inputs
for n in [10000, 100000, 1000000]:
    result, duration = time_test(n)
    print(f"n={n}: result={result}, time={duration:.6f} seconds")

# Use IPython's timing magic
print("\nUsing %timeit:")
%timeit sum(i * i for i in range(10000))

4 Interactive Development Tests

4.1 Code Editing and Re-evaluation

Let’s create a function and then modify it:

def calculate(x, y):
    """Initial version of the function"""
    return x + y

print(f"Initial result: calculate(5, 3) = {calculate(5, 3)}")

Now modify the function and re-evaluate:

# Modified version of the function
def calculate(x, y):
    """Modified version of the function"""
    return x * y

print(f"Modified result: calculate(5, 3) = {calculate(5, 3)}")

4.2 Object Inspection

Test object inspection features:

import inspect

# Create a class to inspect
class TestClass:
    """A test class for inspection"""
    
    def __init__(self, value):
        self.value = value
    
    def double(self):
        """Return twice the value"""
        return self.value * 2
    
    def square(self):
        """Return the square of the value"""
        return self.value ** 2

# Create an instance
obj = TestClass(5)

# Get source code
print("Source code:")
print(inspect.getsource(TestClass))

# Get method list
print("\nMethods:")
for name, method in inspect.getmembers(obj, predicate=inspect.ismethod):
    print(f"  {name}: {method.__doc__}")

# Get attributes
print("\nAttributes:")
for name, value in inspect.getmembers(obj):
    if not name.startswith('_') and not inspect.ismethod(value):
        print(f"  {name}: {value}")

5 Troubleshooting Tools

5.1 Environment Diagnostics

Tools for diagnosing environment issues:

import sys
import os

# Python paths
print("Python path:")
for path in sys.path:
    print(f"  {path}")

# Environment variables
print("\nKey environment variables:")
for var in ['PYTHONPATH', 'VIRTUAL_ENV', 'PATH']:
    if var in os.environ:
        print(f"  {var}: {os.environ[var]}")
    else:
        print(f"  {var}: Not set")

# Module locations
print("\nModule locations:")
for module_name in ['IPython', 'numpy', 'matplotlib']:
    try:
        module = __import__(module_name)
        print(f"  {module_name}: {module.__file__}")
    except ImportError:
        print(f"  {module_name}: Not installed")

5.2 Reset Session

How to reset the IPython session if needed:

# To reset the IPython session, you can use:
# %reset -f

# Or to restart the kernel:
# %kill_kernel
# %connect_info

print("To reset the session, uncomment and run either:")
print("  %reset -f  (clear variables)")
print("  %kill_kernel followed by %connect_info  (restart kernel)")

6 Conclusion

This file has tested the core features of IPython integration with Org mode. If all the code blocks executed correctly, your IPython integration is working as expected.

print("Test suite completed.")
print("If you've reached this point without errors, your IPython integration is working.")