CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-allure-python-commons

Contains the API for end users as well as helper functions and classes to build Allure adapters for Python test frameworks

Overall
score

94%

Overview
Eval results
Files

test-lifecycle.mddocs/

Test Lifecycle Management

Classes and context managers for managing test execution phases, including test cases, fixtures, steps, and containers. These components provide the foundation for tracking test lifecycle events and generating comprehensive test reports.

Capabilities

Steps and Context Management

Context managers and decorators for organizing test execution into hierarchical steps with proper lifecycle tracking.

def step(title):
    """
    Decorator and context manager for test steps.
    
    Can be used as:
    1. Context manager: with allure.step("Step description"):
    2. Decorator: @allure.step("Step description") 
    3. Function decorator: @allure.step (uses function name)
    
    Parameters:
    - title (str or callable): Step title or function to decorate
    
    Returns:
    StepContext instance or decorated function
    """

class StepContext:
    """Context manager for test steps with parameter formatting."""
    
    def __init__(self, title, params):
        """
        Initialize step context.
        
        Parameters:
        - title (str): Step title with optional parameter placeholders
        - params (dict): Parameters for title formatting 
        """
    
    def __enter__(self):
        """Enter step context and start step tracking."""
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Exit step context and stop step tracking.
        
        Parameters:
        - exc_type: Exception type if step failed
        - exc_val: Exception value if step failed  
        - exc_tb: Exception traceback if step failed
        """
    
    def __call__(self, func):
        """
        Use as function decorator.
        
        Parameters:
        - func: Function to wrap with step
        
        Returns:
        Wrapped function with step tracking
        """

Usage Examples:

# Context manager usage
def test_user_registration():
    with allure.step("Open registration page"):
        navigate_to_registration()
    
    with allure.step("Fill user details"):
        fill_username("testuser")
        fill_email("test@example.com")
    
    with allure.step("Submit registration"):
        click_submit()

# Decorator usage with parameters  
@allure.step("Login with username: {username}")
def login_user(username, password):
    enter_credentials(username, password)
    click_login()

# Function decorator usage
@allure.step
def verify_dashboard_loaded():
    assert dashboard.is_visible()

def test_login_flow():
    login_user("testuser", "password123")
    verify_dashboard_loaded()

Attachment Management

Class for attaching files and data to test results, steps, and fixtures.

class Attach:
    """Class for managing test attachments."""
    
    def __call__(self, body, name=None, attachment_type=None, extension=None):
        """
        Attach data to the current test or step.
        
        Parameters:
        - body (str or bytes): Data to attach
        - name (str, optional): Display name for attachment
        - attachment_type (AttachmentType or str, optional): MIME type
        - extension (str, optional): File extension
        """
    
    def file(self, source, name=None, attachment_type=None, extension=None):
        """
        Attach a file to the current test or step.
        
        Parameters:
        - source (str): Path to file to attach
        - name (str, optional): Display name for attachment  
        - attachment_type (AttachmentType or str, optional): MIME type
        - extension (str, optional): File extension override
        """

# Module-level instance
attach: Attach

Usage Examples:

def test_with_attachments():
    # Attach text data
    allure.attach("Test execution log", name="Execution Log", 
                 attachment_type=allure.attachment_type.TEXT)
    
    # Attach JSON data
    test_data = {"user": "testuser", "action": "login"}
    allure.attach(json.dumps(test_data, indent=2), name="Test Data",
                 attachment_type=allure.attachment_type.JSON)
    
    # Attach screenshot file
    allure.attach.file("/tmp/screenshot.png", name="Failure Screenshot",
                      attachment_type=allure.attachment_type.PNG)
    
    # Attach arbitrary file
    allure.attach.file("/tmp/debug.log", name="Debug Log",
                      attachment_type="text/plain")

Fixture Lifecycle Management

Class for managing test fixture execution and lifecycle tracking.

class fixture:
    """Context manager and callable for fixture lifecycle management."""
    
    def __init__(self, fixture_function, parent_uuid=None, name=None):
        """
        Initialize fixture wrapper.
        
        Parameters:
        - fixture_function (callable): The fixture function to wrap
        - parent_uuid (str, optional): UUID of parent container
        - name (str, optional): Custom fixture name
        """
    
    def __call__(self, *args, **kwargs):
        """
        Execute fixture with lifecycle tracking.
        
        Parameters:
        - *args: Positional arguments for fixture
        - **kwargs: Keyword arguments for fixture
        
        Returns:
        Result of fixture function execution
        """
    
    def __enter__(self):
        """Enter fixture context and start tracking."""
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Exit fixture context and stop tracking.
        
        Parameters:
        - exc_type: Exception type if fixture failed
        - exc_val: Exception value if fixture failed
        - exc_tb: Exception traceback if fixture failed
        """

Usage Example:

def database_fixture():
    """Set up test database."""
    db = create_test_database()
    populate_test_data(db)
    return db

def test_with_fixture():
    # Wrap fixture for Allure tracking
    wrapped_fixture = allure_commons.fixture(database_fixture, name="Test Database")
    
    # Execute fixture with tracking
    db = wrapped_fixture()
    
    # Use fixture result
    user = db.get_user("testuser")
    assert user is not None

Test Lifecycle Management

Class for managing individual test execution and lifecycle tracking.

class test:
    """Context manager and callable for test lifecycle management."""
    
    def __init__(self, _test, context):
        """
        Initialize test wrapper.
        
        Parameters:
        - _test (callable): The test function to wrap
        - context (dict): Test execution context
        """
    
    def __call__(self, *args, **kwargs):
        """
        Execute test with lifecycle tracking.
        
        Parameters:
        - *args: Positional arguments for test
        - **kwargs: Keyword arguments for test
        
        Returns:
        Result of test function execution
        """
    
    def __enter__(self):
        """Enter test context and start tracking."""
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        Exit test context and stop tracking.
        
        Parameters:
        - exc_type: Exception type if test failed
        - exc_val: Exception value if test failed
        - exc_tb: Exception traceback if test failed
        """

Advanced Lifecycle Management

Complete lifecycle management class for complex test execution scenarios.

class AllureLifecycle:
    """Main lifecycle management class for test execution tracking."""
    
    def __init__(self):
        """Initialize lifecycle manager with internal item storage."""
    
    def schedule_test_case(self, uuid=None):
        """
        Context manager to schedule a test case.
        
        Parameters:
        - uuid (str, optional): Custom UUID for test case
        
        Yields:
        TestResult: Test result object for configuration
        """
    
    def update_test_case(self, uuid=None):
        """
        Context manager to update test case properties.
        
        Parameters:
        - uuid (str, optional): UUID of test case to update
        
        Yields:
        TestResult: Test result object for modification
        """
    
    def write_test_case(self, uuid=None):
        """
        Write test case to registered reporters.
        
        Parameters:
        - uuid (str, optional): UUID of test case to write
        """
    
    def start_step(self, parent_uuid=None, uuid=None):
        """
        Context manager to start a test step.
        
        Parameters:
        - parent_uuid (str, optional): UUID of parent item
        - uuid (str, optional): Custom UUID for step
        
        Yields:
        TestStepResult: Step result object for configuration
        """
    
    def update_step(self, uuid=None):
        """
        Context manager to update step properties.
        
        Parameters:
        - uuid (str, optional): UUID of step to update
        
        Yields:
        TestStepResult: Step result object for modification
        """
    
    def stop_step(self, uuid=None):
        """
        Stop step execution and set end timestamp.
        
        Parameters:
        - uuid (str, optional): UUID of step to stop
        """
    
    def start_container(self, uuid=None):
        """
        Context manager to start a test result container.
        
        Parameters:
        - uuid (str, optional): Custom UUID for container
        
        Yields:
        TestResultContainer: Container object for configuration
        """
    
    def containers(self):
        """
        Generator yielding all active containers.
        
        Yields:
        TestResultContainer: Active container objects
        """
    
    def update_container(self, uuid=None):
        """
        Context manager to update container properties.
        
        Parameters:
        - uuid (str, optional): UUID of container to update
        
        Yields:
        TestResultContainer: Container object for modification
        """
    
    def write_container(self, uuid=None):
        """
        Write container to registered reporters.
        
        Parameters:
        - uuid (str, optional): UUID of container to write
        """
    
    def start_before_fixture(self, parent_uuid=None, uuid=None):
        """
        Context manager to start a before fixture.
        
        Parameters:
        - parent_uuid (str, optional): UUID of parent container
        - uuid (str, optional): Custom UUID for fixture
        
        Yields:
        TestBeforeResult: Before fixture result object
        """
    
    def update_before_fixture(self, uuid=None):
        """
        Context manager to update before fixture properties.
        
        Parameters:
        - uuid (str, optional): UUID of fixture to update
        
        Yields:
        TestBeforeResult: Before fixture result object
        """
    
    def stop_before_fixture(self, uuid=None):
        """
        Stop before fixture execution.
        
        Parameters:
        - uuid (str, optional): UUID of fixture to stop
        """
    
    def start_after_fixture(self, parent_uuid=None, uuid=None):
        """
        Context manager to start an after fixture.
        
        Parameters:
        - parent_uuid (str, optional): UUID of parent container
        - uuid (str, optional): Custom UUID for fixture
        
        Yields:
        TestAfterResult: After fixture result object
        """
    
    def update_after_fixture(self, uuid=None):
        """
        Context manager to update after fixture properties.
        
        Parameters:
        - uuid (str, optional): UUID of fixture to update
        
        Yields:
        TestAfterResult: After fixture result object
        """
    
    def stop_after_fixture(self, uuid=None):
        """
        Stop after fixture execution.
        
        Parameters:
        - uuid (str, optional): UUID of fixture to stop
        """
    
    def attach_file(self, uuid, source, name=None, attachment_type=None, 
                   extension=None, parent_uuid=None):
        """
        Attach a file to a test item.
        
        Parameters:
        - uuid (str): Attachment UUID
        - source (str): Path to source file
        - name (str, optional): Display name
        - attachment_type (AttachmentType, optional): MIME type
        - extension (str, optional): File extension
        - parent_uuid (str, optional): Parent item UUID
        """
    
    def attach_data(self, uuid, body, name=None, attachment_type=None,
                   extension=None, parent_uuid=None):
        """
        Attach data to a test item.
        
        Parameters:
        - uuid (str): Attachment UUID
        - body (str or bytes): Data to attach
        - name (str, optional): Display name
        - attachment_type (AttachmentType, optional): MIME type
        - extension (str, optional): File extension
        - parent_uuid (str, optional): Parent item UUID
        """

Usage Example:

from allure_commons.lifecycle import AllureLifecycle

def custom_test_runner():
    lifecycle = AllureLifecycle()
    
    # Schedule and configure test case
    with lifecycle.schedule_test_case() as test_result:
        test_result.name = "Custom Test"
        test_result.description = "Test executed by custom runner"
    
    # Add test steps
    with lifecycle.start_step() as step:
        step.name = "Initialize test data"
        # Execute step logic
    
    with lifecycle.start_step() as step:
        step.name = "Execute test scenario"
        # Execute step logic
        
        # Attach step data
        lifecycle.attach_data(
            uuid="step-data",
            body="Step execution details",
            name="Step Data"
        )
    
    # Write results
    lifecycle.write_test_case()

Install with Tessl CLI

npx tessl i tessl/pypi-allure-python-commons

docs

data-models.md

index.md

plugin-system.md

test-decorators.md

test-lifecycle.md

utilities.md

tile.json