Back to Repositories

Testing Python Decorator Implementation in AutoGPT

This test suite validates custom Python decorators for performance timing and error logging in AutoGPT. It ensures robust function instrumentation and error handling capabilities through targeted unit tests.

Test Coverage Overview

The test suite provides comprehensive coverage of two key decorators: @time_measured and @error_logged.

Key areas tested include:
  • CPU and wall time measurement accuracy
  • Error handling and logging functionality
  • Return value validation for both successful and error cases
  • Integration with Python’s built-in time module

Implementation Analysis

The testing approach uses pytest to validate decorator behavior through isolated unit tests. The implementation leverages Python’s decorator pattern to inject timing and error handling capabilities around target functions.

Technical patterns include:
  • Function wrapping with metadata preservation
  • Time measurement using system calls
  • Exception handling with graceful degradation

Technical Details

Testing infrastructure includes:
  • pytest as the primary testing framework
  • Python’s time module for performance measurements
  • Custom decorator implementations (@time_measured, @error_logged)
  • Assert statements for validation
  • Simulated delays using time.sleep()

Best Practices Demonstrated

The test suite exemplifies several testing best practices for decorator validation.

Notable practices include:
  • Isolation of decorator functionality
  • Explicit timing thresholds
  • Error case handling
  • Clear test function naming
  • Separation of timing and error handling concerns

significant-gravitas/autogpt

autogpt_platform/backend/test/util/test_decorator.py

            
import time

from backend.util.decorator import error_logged, time_measured


@time_measured
def example_function(a: int, b: int, c: int) -> int:
    time.sleep(0.5)
    return a + b + c


@error_logged
def example_function_with_error(a: int, b: int, c: int) -> int:
    raise ValueError("This is a test error")


def test_timer_decorator():
    info, res = example_function(1, 2, 3)
    assert info.cpu_time >= 0
    assert info.wall_time >= 0.4
    assert res == 6


def test_error_decorator():
    res = example_function_with_error(1, 2, 3)
    assert res is None