"""Tests for batch_runner module.""" import os import sys import tempfile from unittest.mock import patch, MagicMock sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from batch_runner import run_batch, parse_tickers, _write_summary # ── parse_tickers tests ────────────────────────────────────────── def test_parse_comma_separated(): result = parse_tickers("AAPL, MSFT, GOOG") assert result == ["AAPL", "MSFT", "GOOG"] def test_parse_newline_separated(): result = parse_tickers("AAPL\nMSFT\nGOOG") assert result == ["AAPL", "MSFT", "GOOG"] def test_parse_mixed_separators(): result = parse_tickers("AAPL, MSFT\nGOOG\r\nAMZN") assert result == ["AAPL", "MSFT", "GOOG", "AMZN"] def test_parse_deduplicates(): result = parse_tickers("AAPL, MSFT, AAPL, GOOG, MSFT") assert result == ["AAPL", "MSFT", "GOOG"] def test_parse_uppercases(): result = parse_tickers("aapl, msft") assert result == ["AAPL", "MSFT"] def test_parse_empty_string(): result = parse_tickers("") assert result == [] def test_parse_whitespace_only(): result = parse_tickers(" \n \r\n ") assert result == [] def test_parse_single_ticker(): result = parse_tickers("AAPL") assert result == ["AAPL"] def test_parse_strips_whitespace(): result = parse_tickers(" AAPL , MSFT ") assert result == ["AAPL", "MSFT"] # ── _write_summary tests ──────────────────────────────────────── def test_write_summary_creates_file(): results = [ {"success": True, "ticker": "AAPL", "company_name": "Apple Inc.", "elapsed_seconds": 12.5, "spreading_path": "/tmp/AAPL.xlsx"}, {"success": False, "ticker": "BADTK", "elapsed_seconds": 1.0, "error": "Ticker not found"}, ] with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f: path = f.name try: _write_summary(results, 13.5, path) assert os.path.exists(path) content = open(path).read() assert "AAPL" in content assert "BADTK" in content assert "Succeeded" in content assert "Failed" in content assert "Apple Inc." in content assert "Ticker not found" in content finally: os.unlink(path) def test_write_summary_all_success(): results = [ {"success": True, "ticker": "AAPL", "company_name": "Apple Inc.", "elapsed_seconds": 10.0}, {"success": True, "ticker": "MSFT", "company_name": "Microsoft Corp.", "elapsed_seconds": 11.0}, ] with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f: path = f.name try: _write_summary(results, 21.0, path) content = open(path).read() assert "Succeeded: 2" in content assert "Failed: 0" in content finally: os.unlink(path) # ── run_batch tests (mocked pipeline) ─────────────────────────── def test_run_batch_calls_pipeline_per_ticker(): """Verify run_batch calls app_runner.run_pipeline once per ticker.""" call_log = [] def mock_pipeline(**kwargs): call_log.append(kwargs["ticker"]) # Simulate success via on_complete callback kwargs["on_complete"]({ "success": True, "ticker": kwargs["ticker"], "company_name": f"{kwargs['ticker']} Inc.", "elapsed_seconds": 1.0, }) with patch("batch_runner.app_runner") as mock_ar: mock_ar.run_pipeline = mock_pipeline with tempfile.TemporaryDirectory() as tmpdir: results = run_batch(["AAPL", "MSFT"], tmpdir) assert len(results) == 2 assert call_log == ["AAPL", "MSFT"] assert results[0]["success"] is True assert results[1]["success"] is True def test_run_batch_handles_failure_gracefully(): """One ticker failing should not stop the batch.""" def mock_pipeline(**kwargs): if kwargs["ticker"] == "BADTK": raise ValueError("Ticker not found") kwargs["on_complete"]({ "success": True, "ticker": kwargs["ticker"], "company_name": f"{kwargs['ticker']} Inc.", "elapsed_seconds": 1.0, }) with patch("batch_runner.app_runner") as mock_ar: mock_ar.run_pipeline = mock_pipeline with tempfile.TemporaryDirectory() as tmpdir: results = run_batch(["AAPL", "BADTK", "GOOG"], tmpdir) assert len(results) == 3 assert results[0]["success"] is True assert results[1]["success"] is False assert "Ticker not found" in results[1]["error"] assert results[2]["success"] is True def test_run_batch_creates_subdirectories(): """Each ticker should get its own subdirectory.""" def mock_pipeline(**kwargs): # Verify output_dir contains the ticker assert kwargs["ticker"] in kwargs["output_dir"] kwargs["on_complete"]({ "success": True, "ticker": kwargs["ticker"], "elapsed_seconds": 0.5, }) with patch("batch_runner.app_runner") as mock_ar: mock_ar.run_pipeline = mock_pipeline with tempfile.TemporaryDirectory() as tmpdir: results = run_batch(["AAPL", "MSFT"], tmpdir) assert os.path.exists(os.path.join(tmpdir, "AAPL")) assert os.path.exists(os.path.join(tmpdir, "MSFT")) def test_run_batch_writes_summary(): """Batch should produce a batch_summary.txt.""" def mock_pipeline(**kwargs): kwargs["on_complete"]({ "success": True, "ticker": kwargs["ticker"], "elapsed_seconds": 0.5, }) with patch("batch_runner.app_runner") as mock_ar: mock_ar.run_pipeline = mock_pipeline with tempfile.TemporaryDirectory() as tmpdir: run_batch(["AAPL"], tmpdir) summary_path = os.path.join(tmpdir, "batch_summary.txt") assert os.path.exists(summary_path) content = open(summary_path).read() assert "AAPL" in content def test_run_batch_passes_options(): """Options dict should be forwarded to the pipeline.""" captured = {} def mock_pipeline(**kwargs): captured.update(kwargs) kwargs["on_complete"]({"success": True, "ticker": kwargs["ticker"], "elapsed_seconds": 0.5}) with patch("batch_runner.app_runner") as mock_ar: mock_ar.run_pipeline = mock_pipeline with tempfile.TemporaryDirectory() as tmpdir: run_batch(["TEST"], tmpdir, options={"years": 3, "eqr": True}) assert captured["years"] == 3 assert captured["eqr"] is True def test_run_batch_empty_tickers(): """Empty ticker list should return empty results.""" with tempfile.TemporaryDirectory() as tmpdir: results = run_batch([], tmpdir) assert results == [] def test_run_batch_progress_callback(): """Progress callback should be called for each ticker.""" progress_calls = [] def mock_pipeline(**kwargs): kwargs["on_complete"]({"success": True, "ticker": kwargs["ticker"], "elapsed_seconds": 0.5}) def on_progress(ticker, stage, message, is_error): progress_calls.append((ticker, stage)) with patch("batch_runner.app_runner") as mock_ar: mock_ar.run_pipeline = mock_pipeline with tempfile.TemporaryDirectory() as tmpdir: run_batch(["AAPL"], tmpdir, on_progress=on_progress) # Should have at least BATCH/init, AAPL/start, AAPL/done, BATCH/done tickers_in_calls = [t for t, s in progress_calls] assert "BATCH" in tickers_in_calls assert "AAPL" in tickers_in_calls