1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
|
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.
"""
TextCallbackWorker end-to-end test
-----------------------------------
This test validates the TextCallbackWorker using real-world scenarios,
including reading signal data from CSV files with progress tracking and
cancellation support.
"""
# pylint: disable=invalid-name # Allows short reference names like x, y, ...
# guitest: skip
from __future__ import annotations
import tempfile
from pathlib import Path
import numpy as np
import pytest
from sigima.io.signal.formats import CSVSignalFormat
from sigima.worker import TextCallbackWorker
def create_large_csv_file(filepath: Path, nrows: int = 1000) -> None:
"""Create a large CSV file for testing progress tracking.
Args:
filepath: Path to the CSV file
nrows: Number of rows to generate
"""
with open(filepath, "w", encoding="utf-8") as f:
# Write header
f.write("x,y\n")
# Write data
for i in range(nrows):
f.write(f"{i},{np.sin(i / 10.0)}\n")
class CancelingWorker(TextCallbackWorker):
"""Worker that cancels itself after a certain progress threshold."""
def __init__(self, cancel_threshold: float = 0.5) -> None:
"""Initialize the canceling worker.
Args:
cancel_threshold: Progress value at which to cancel (0.0-1.0)
"""
super().__init__()
self.cancel_threshold = cancel_threshold
self.progress_calls = []
def set_progress(self, value: float) -> None:
"""Set progress and cancel if threshold is reached.
Args:
value: Progress value (0.0-1.0)
"""
super().set_progress(value)
self.progress_calls.append(value)
if value >= self.cancel_threshold:
self.cancel()
def test_worker_basic_functionality():
"""Test basic TextCallbackWorker functionality."""
worker = TextCallbackWorker()
# Initial state
assert worker.get_progress() == 0.0
assert not worker.was_canceled()
# Set progress
worker.set_progress(0.5)
assert worker.get_progress() == 0.5
assert not worker.was_canceled()
# Progress clamping (below 0)
worker.set_progress(-0.1)
assert worker.get_progress() == 0.0
# Progress clamping (above 1)
worker.set_progress(1.5)
assert worker.get_progress() == 1.0
# Cancel
worker.cancel()
assert worker.was_canceled()
def test_worker_with_signal_reading(capsys):
"""End-to-end test: read signal data with progress tracking."""
with tempfile.TemporaryDirectory() as tmpdir:
# Create a larger test CSV file to ensure chunked reading
csv_file = Path(tmpdir) / "test_signal.csv"
nrows = 50000 # Large enough to trigger multiple chunks
create_large_csv_file(csv_file, nrows=nrows)
# Read with worker using the CSV format directly
worker = TextCallbackWorker()
csv_format = CSVSignalFormat()
signals = csv_format.read(str(csv_file), worker=worker)
# Verify the signal was read correctly
assert len(signals) == 1 # Single signal from x,y columns
assert signals[0].data.shape[0] == nrows
# Verify progress reached 100%
assert worker.get_progress() == 1.0
assert not worker.was_canceled()
# Check that progress messages were printed
captured = capsys.readouterr()
assert "[sigima] Progress:" in captured.out
assert "100%" in captured.out
def test_worker_with_cancellation():
"""End-to-end test: cancel signal reading mid-operation."""
with tempfile.TemporaryDirectory() as tmpdir:
# Create a larger test CSV file to ensure chunked reading
csv_file = Path(tmpdir) / "test_signal.csv"
nrows = 50000 # Large enough to trigger multiple chunks
create_large_csv_file(csv_file, nrows=nrows)
# Use a worker that cancels at 50% progress
worker = CancelingWorker(cancel_threshold=0.5)
csv_format = CSVSignalFormat()
signals = csv_format.read(str(csv_file), worker=worker)
# Verify the operation was canceled
assert worker.was_canceled()
assert len(worker.progress_calls) > 0
# The signals should still be returned (partial result)
# but may have fewer rows than expected
assert len(signals) >= 1
assert signals[0].data.shape[0] <= nrows
def test_worker_without_output(capsys):
"""Test worker progress output is correctly formatted."""
worker = TextCallbackWorker()
# Capture output
worker.set_progress(0.0)
worker.set_progress(0.25)
worker.set_progress(0.5)
worker.set_progress(0.75)
worker.set_progress(1.0)
captured = capsys.readouterr()
# Verify progress messages
assert "[sigima] Progress: 0%" in captured.out
assert "[sigima] Progress: 25%" in captured.out
assert "[sigima] Progress: 50%" in captured.out
assert "[sigima] Progress: 75%" in captured.out
assert "[sigima] Progress: 100%" in captured.out
def test_worker_concurrent_operations():
"""Test multiple workers can operate independently."""
worker1 = TextCallbackWorker()
worker2 = TextCallbackWorker()
worker1.set_progress(0.3)
worker2.set_progress(0.7)
assert worker1.get_progress() == 0.3
assert worker2.get_progress() == 0.7
worker1.cancel()
assert worker1.was_canceled()
assert not worker2.was_canceled()
if __name__ == "__main__":
# Run pytest with verbose output
pytest.main([__file__, "-v"])
|