Skip to content

Automate browser based workflows with AI

Move tests/unit_tests into tests/unit (#8646)

Cindy Li61dd1acd9f2f
diff --git a/.github/sync.yml b/.github/sync.yml
index f8866018e..772c11caf 100644
--- a/.github/sync.yml
+++ b/.github/sync.yml
@@ -39,9 +39,6 @@ Skyvern-AI/skyvern-cloud:
- source: tests/unit/
dest: tests/unit/
deleteOrphaned: true
- - source: tests/unit_tests/
- dest: tests/unit_tests/
- deleteOrphaned: true
- source: tests/smoke_tests/
dest: tests/smoke_tests/
deleteOrphaned: true
diff --git a/CLAUDE.md b/CLAUDE.md
index 8010324be..eaf68e4b0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -81,7 +81,7 @@ Configure via environment variables or the interactive `skyvern init` wizard:
- `SECONDARY_LLM_KEY` for lightweight agent operations
### Testing Strategy
-- Unit tests in `tests/unit_tests/`
+- Unit tests in `tests/unit/`
- Integration tests require browser automation setup
- Use `pytest` with async support for testing
diff --git a/tests/test_runtime_config_route.py b/tests/test_runtime_config_route.py
index 44098a4bd..e52d09515 100644
--- a/tests/test_runtime_config_route.py
+++ b/tests/test_runtime_config_route.py
@@ -4,7 +4,7 @@ from types import ModuleType, SimpleNamespace
import pytest
-from tests.unit_tests._stub_streaming import import_with_stubs
+from tests.unit._stub_streaming import import_with_stubs
class _FakeAPIRouter:
diff --git a/tests/unit_tests/_stub_streaming.py b/tests/unit/_stub_streaming.py
similarity index 100%
rename from tests/unit_tests/_stub_streaming.py
rename to tests/unit/_stub_streaming.py
diff --git a/tests/unit_tests/__init__.py b/tests/unit_tests/__init__.py
deleted file mode 100644
index 94bf69b47..000000000
--- a/tests/unit_tests/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-import sys
-from pathlib import Path
-
-ROOT = Path(__file__).resolve().parents[1]
-sys.path.insert(0, str(ROOT))
diff --git a/tests/unit_tests/test_alembic_loop.py b/tests/unit_tests/test_alembic_loop.py
deleted file mode 100644
index d0c733c97..000000000
--- a/tests/unit_tests/test_alembic_loop.py
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/usr/bin/env python3
-"""Test script to verify alembic works correctly with an existing event loop."""
-
-import asyncio
-import os
-import subprocess
-import sys
-
-import pytest
-
-
-async def test_alembic_with_running_loop():
- """Test alembic migration execution within an existing event loop."""
- print("Testing alembic migration with existing event loop...")
-
- # Change to the project directory
- os.chdir(os.path.dirname(__file__))
-
- # Run alembic command in a subprocess
- try:
- result = subprocess.run(
- [sys.executable, "-m", "alembic", "current"], capture_output=True, text=True, timeout=30
- )
-
- print(f"Return code: {result.returncode}")
- print(f"Stdout: {result.stdout}")
- if result.stderr:
- print(f"Stderr: {result.stderr}")
-
- return result.returncode == 0
- except subprocess.TimeoutExpired:
- print("ERROR: Alembic command timed out!")
- return False
- except Exception as e:
- print(f"ERROR: {e}")
- return False
-
-
-if __name__ == "__main__":
- # This creates an event loop and runs alembic within it
- success = asyncio.run(test_alembic_with_running_loop())
- print(f"Test {'PASSED' if success else 'FAILED'}")
- sys.exit(0 if success else 1)
diff --git a/tests/unit_tests/test_file_parser_block.py b/tests/unit_tests/test_file_parser_block.py
deleted file mode 100644
index f0c36175a..000000000
--- a/tests/unit_tests/test_file_parser_block.py
+++ /dev/null
@@ -1,260 +0,0 @@
-import os
-import tempfile
-from datetime import datetime
-from unittest.mock import MagicMock, patch
-
-import pandas as pd
-import pytest
-
-from skyvern.forge import app
-from skyvern.forge.forge_app_initializer import start_forge_app
-from skyvern.forge.sdk.workflow.models.block import FileParserBlock, FileType
-from skyvern.forge.sdk.workflow.models.parameter import OutputParameter
-
-
[email protected](scope="module", autouse=True)
-def setup_forge_app():
- start_forge_app()
- yield
-
-
-class TestFileParserBlock:
- @pytest.fixture
- def file_parser_block(self):
- """Create a basic FileParserBlock instance for testing."""
- # Create a mock OutputParameter with all required fields
- mock_output_parameter = MagicMock(spec=OutputParameter)
- mock_output_parameter.parameter_type = "output"
- mock_output_parameter.key = "test_output"
- mock_output_parameter.output_parameter_id = "test_id"
- mock_output_parameter.workflow_id = "test_workflow_id"
- mock_output_parameter.created_at = datetime.now()
- mock_output_parameter.modified_at = datetime.now()
- mock_output_parameter.deleted_at = None
-
- return FileParserBlock(
- label="test_parser", output_parameter=mock_output_parameter, file_url="test.csv", file_type=FileType.CSV
- )
-
- @pytest.fixture
- def csv_file(self):
- """Create a temporary CSV file for testing."""
- with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
- f.write("name,age,city\nJohn,30,New York\nJane,25,Boston")
- temp_file = f.name
-
- yield temp_file
- os.unlink(temp_file)
-
- @pytest.fixture
- def excel_file(self):
- """Create a temporary Excel file for testing."""
- df = pd.DataFrame({"name": ["John", "Jane"], "age": [30, 25], "city": ["New York", "Boston"]})
-
- with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as f:
- df.to_excel(f.name, index=False)
- temp_file = f.name
-
- yield temp_file
- os.unlink(temp_file)
-
- @pytest.fixture
- def tsv_file(self):
- """Create a temporary TSV file for testing."""
- with tempfile.NamedTemporaryFile(mode="w", suffix=".tsv", delete=False) as f:
- f.write("name\tage\tcity\nJohn\t30\tNew York\nJane\t25\tBoston")
- temp_file = f.name
-
- yield temp_file
- os.unlink(temp_file)
-
- def test_file_type_enum_values(self):
- """Test that FileType enum has the expected values."""
- assert FileType.CSV == "csv"
- assert FileType.EXCEL == "excel"
- assert FileType.PDF == "pdf"
-
- def test_file_parser_block_initialization(self, file_parser_block):
- """Test that FileParserBlock initializes correctly."""
- assert file_parser_block.label == "test_parser"
- assert file_parser_block.file_url == "test.csv"
- assert file_parser_block.file_type == FileType.CSV
- assert file_parser_block.json_schema is None
-
- def test_file_parser_block_with_schema(self):
- """Test that FileParserBlock can be initialized with a schema."""
- schema = {"type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}}
-
- # Create a mock OutputParameter
- mock_output_parameter = MagicMock(spec=OutputParameter)
- mock_output_parameter.parameter_type = "output"
- mock_output_parameter.key = "test_output"
- mock_output_parameter.output_parameter_id = "test_id"
- mock_output_parameter.workflow_id = "test_workflow_id"
- mock_output_parameter.created_at = datetime.now()
- mock_output_parameter.modified_at = datetime.now()
- mock_output_parameter.deleted_at = None
-
- block = FileParserBlock(
- label="test_parser",
- output_parameter=mock_output_parameter,
- file_url="test.csv",
- file_type=FileType.CSV,
- json_schema=schema,
- )
-
- assert block.json_schema == schema
-
- @pytest.mark.asyncio
- async def test_parse_csv_file(self, file_parser_block, csv_file):
- """Test CSV file parsing."""
- result = await file_parser_block._parse_csv_file(csv_file)
-
- expected = [{"name": "John", "age": "30", "city": "New York"}, {"name": "Jane", "age": "25", "city": "Boston"}]
-
- assert result == expected
-
- @pytest.mark.asyncio
- async def test_parse_excel_file(self, file_parser_block, excel_file):
- """Test Excel file parsing."""
- result = await file_parser_block._parse_excel_file(excel_file)
-
- expected = [{"name": "John", "age": 30, "city": "New York"}, {"name": "Jane", "age": 25, "city": "Boston"}]
-
- assert result == expected
-
- @pytest.mark.asyncio
- async def test_parse_tsv_file(self, file_parser_block, tsv_file):
- """Test TSV file parsing."""
- result = await file_parser_block._parse_csv_file(tsv_file)
-
- expected = [{"name": "John", "age": "30", "city": "New York"}, {"name": "Jane", "age": "25", "city": "Boston"}]
-
- assert result == expected
-
- @pytest.mark.asyncio
- async def test_validate_csv_file_type(self, file_parser_block, csv_file):
- """Test CSV file type validation."""
- # Should not raise an exception
- file_parser_block.validate_file_type("test.csv", csv_file)
-
- @pytest.mark.asyncio
- async def test_validate_excel_file_type(self, file_parser_block, excel_file):
- """Test Excel file type validation."""
- file_parser_block.file_type = FileType.EXCEL
- # Should not raise an exception
- file_parser_block.validate_file_type("test.xlsx", excel_file)
-
- @pytest.mark.asyncio
- async def test_validate_invalid_csv_file(self, file_parser_block):
- """Test validation of invalid CSV file."""
- # Create a binary file that's definitely not CSV
- with tempfile.NamedTemporaryFile(mode="wb", suffix=".csv", delete=False) as f:
- f.write(b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")
- temp_file = f.name
-
- try:
- with pytest.raises(Exception):
- file_parser_block.validate_file_type("test.csv", temp_file)
- finally:
- os.unlink(temp_file)
-
- @pytest.mark.asyncio
- async def test_extract_with_ai_with_schema(self, file_parser_block):
- """Test AI extraction with a provided schema."""
- schema = {
- "type": "object",
- "properties": {
- "extracted_data": {
- "type": "object",
- "properties": {
- "names": {"type": "array", "items": {"type": "string"}},
- "total_count": {"type": "integer"},
- },
- }
- },
- }
-
- file_parser_block.json_schema = schema
-
- # Mock the LLM response
- mock_response = {"extracted_data": {"names": ["John", "Jane"], "total_count": 2}}
-
- with patch.object(object.__getattribute__(app, "_inst"), "LLM_API_HANDLER") as mock_llm:
- mock_llm.return_value = mock_response
-
- with patch("skyvern.forge.sdk.workflow.models.block.prompt_engine.load_prompt") as mock_prompt:
- mock_prompt.return_value = "mocked prompt"
-
- result = await file_parser_block._extract_with_ai([{"name": "John"}, {"name": "Jane"}], MagicMock())
-
- assert result == mock_response
- mock_llm.assert_called_once()
- mock_prompt.assert_called_once()
-
- @pytest.mark.asyncio
- async def test_extract_with_ai_without_schema(self, file_parser_block):
- """Test AI extraction without a provided schema (should use default)."""
- # Mock the LLM response
- mock_response = {"output": {"summary": "Extracted data from file"}}
-
- with patch.object(object.__getattribute__(app, "_inst"), "LLM_API_HANDLER") as mock_llm:
- mock_llm.return_value = mock_response
-
- with patch("skyvern.forge.sdk.workflow.models.block.prompt_engine.load_prompt") as mock_prompt:
- mock_prompt.return_value = "mocked prompt"
-
- result = await file_parser_block._extract_with_ai("Some text content", MagicMock())
-
- assert result == mock_response
- # Should NOT mutate the instance - json_schema should remain None
- assert file_parser_block.json_schema is None
- mock_llm.assert_called_once()
- mock_prompt.assert_called_once()
-
- def test_detect_file_type_from_url(self, file_parser_block):
- """Test file type detection based on URL extension."""
- # Test Excel files
- assert file_parser_block._detect_file_type_from_url("https://example.com/data.xlsx") == FileType.EXCEL
- assert file_parser_block._detect_file_type_from_url("https://example.com/data.xls") == FileType.EXCEL
- assert file_parser_block._detect_file_type_from_url("https://example.com/data.xlsm") == FileType.EXCEL
-
- # Test PDF files
- assert file_parser_block._detect_file_type_from_url("https://example.com/document.pdf") == FileType.PDF
-
- # Test CSV files (default)
- assert file_parser_block._detect_file_type_from_url("https://example.com/data.csv") == FileType.CSV
- assert file_parser_block._detect_file_type_from_url("https://example.com/data.tsv") == FileType.CSV
- assert file_parser_block._detect_file_type_from_url("https://example.com/data.txt") == FileType.CSV
- assert file_parser_block._detect_file_type_from_url("https://example.com/data") == FileType.CSV
-
- def test_clean_dataframe_for_json(self, file_parser_block):
- """Test DataFrame cleaning for JSON serialization."""
- # Create a DataFrame with NaN, NaT, and timestamp values
- df = pd.DataFrame(
- {
- "OrderDate": ["2018-01-01", pd.NaT, "2018-01-03"],
- "Region": ["North", "South", pd.NA],
- "Sales": [1000.0, pd.NA, 3000.0],
- "Timestamp": [pd.Timestamp("2018-01-01"), pd.NaT, pd.Timestamp("2018-01-03")],
- }
- )
-
- # Clean the DataFrame
- result = file_parser_block._clean_dataframe_for_json(df)
-
- # Check that NaN and NaT values are converted to "nan" string
- assert result[0]["OrderDate"] == "2018-01-01"
- assert result[0]["Region"] == "North"
- assert result[0]["Sales"] == 1000.0
- assert result[0]["Timestamp"] == "2018-01-01T00:00:00"
-
- assert result[1]["OrderDate"] == "nan"
- assert result[1]["Region"] == "South"
- assert result[1]["Sales"] == "nan"
- assert result[1]["Timestamp"] == "nan"
-
- assert result[2]["OrderDate"] == "2018-01-03"
- assert result[2]["Region"] == "nan"
- assert result[2]["Sales"] == 3000.0
- assert result[2]["Timestamp"] == "2018-01-03T00:00:00"
diff --git a/tests/unit_tests/test_gemini_flex_config.py b/tests/unit_tests/test_gemini_flex_config.py
deleted file mode 100644
index f057c8e1e..000000000
--- a/tests/unit_tests/test_gemini_flex_config.py
+++ /dev/null
@@ -1,68 +0,0 @@
-import dataclasses
-import importlib
-from collections.abc import Iterator
-
-import pytest
-
-from skyvern import config
-from skyvern.config import Settings
-from skyvern.forge.sdk.api.llm import config_registry
-from skyvern.forge.sdk.settings_manager import SettingsManager
-from skyvern.schemas.llm import LLMConfig
-
-
-def gemini_registry(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
- """ENABLE_GEMINI is off by default, so the Gemini block only registers on a reload with it
- set. The registry dict, config_registry's module-level `settings` binding and SettingsManager
- are all process-global; snapshot and restore the three so the reload can't leak into other
- tests (or be leaked into, depending on execution order).
- """
- previous_settings = SettingsManager.get_settings()
- previous_configs = dict(config_registry.LLMConfigRegistry._configs)
- previous_module_settings = config_registry.settings
-
- gemini_settings = Settings(ENABLE_GEMINI=True, GEMINI_API_KEY="test-key")
- SettingsManager.set_settings(gemini_settings)
- monkeypatch.setattr(config, "settings", gemini_settings)
- config_registry.LLMConfigRegistry._configs.clear()
- importlib.reload(config_registry)
- try:
- yield
- finally:
- SettingsManager.set_settings(previous_settings)
- config_registry.LLMConfigRegistry._configs.clear()
- config_registry.LLMConfigRegistry._configs.update(previous_configs)
- config_registry.settings = previous_module_settings
-
-
-def test_gemini_3_1_flash_lite_flex_requests_the_flex_service_tier(gemini_registry: None) -> None:
- assert config_registry.LLMConfigRegistry.is_registered("GEMINI_3.1_FLASH_LITE_FLEX")
-
- flex = config_registry.LLMConfigRegistry.get_config("GEMINI_3.1_FLASH_LITE_FLEX")
- assert isinstance(flex, LLMConfig)
- assert flex.model_name == "gemini/gemini-3.1-flash-lite"
- assert flex.required_env_vars == ["GEMINI_API_KEY"]
- assert flex.litellm_params is not None
- assert flex.litellm_params["service_tier"] == "flex"
- assert flex.litellm_params["timeout"] == config_registry.FLEX_EXECUTION_TIMEOUT_SECONDS
-
-
-def test_gemini_3_1_flash_lite_flex_differs_from_standard_only_by_tier(gemini_registry: None) -> None:
- """The flex twin must stay a pure tier swap: any other divergence (model id, token ceiling,
- thinking level) would make flex and standard runs silently non-comparable."""
- flex = config_registry.LLMConfigRegistry.get_config("GEMINI_3.1_FLASH_LITE_FLEX")
- standard = config_registry.LLMConfigRegistry.get_config("GEMINI_3.1_FLASH_LITE")
- assert isinstance(flex, LLMConfig)
- assert isinstance(standard, LLMConfig)
-
- flex_fields = dataclasses.asdict(flex)
- standard_fields = dataclasses.asdict(standard)
- assert flex_fields.pop("litellm_params") is not None
- assert standard_fields.pop("litellm_params") is not None
- assert flex_fields == standard_fields
-
- assert flex.litellm_params is not None
- assert standard.litellm_params is not None
- tier_only = {k: v for k, v in flex.litellm_params.items() if k not in ("service_tier", "timeout")}
- assert tier_only == dict(standard.litellm_params)
diff --git a/tests/unit_tests/test_id_generator.py b/tests/unit_tests/test_id_generator.py
deleted file mode 100644
index 8221664bf..000000000
--- a/tests/unit_tests/test_id_generator.py
+++ /dev/null
@@ -1,234 +0,0 @@
-import re
-
-import pytest
-
-from skyvern.forge.sdk.db.id import (
- ACTION_PREFIX,
- ARTIFACT_PREFIX,
- BASE_EPOCH,
- CREDENTIAL_PREFIX,
- DEBUG_SESSION_PREFIX,
- FOLDER_PREFIX,
- ORG_PREFIX,
- SEQUENCE_BITS,
- SEQUENCE_MAX,
- STEP_PREFIX,
- TASK_PREFIX,
- TASK_V2_ID,
- THOUGHT_ID,
- TIMESTAMP_BITS,
- TOTP_CODE_PREFIX,
- USER_PREFIX,
- VERSION,
- VERSION_BITS,
- WORKER_ID_BITS,
- WORKFLOW_PREFIX,
- WORKFLOW_RUN_BLOCK_PREFIX,
- WORKFLOW_RUN_PREFIX,
- _mask_shift,
- current_time,
- current_time_ms,
- generate_action_id,
- generate_artifact_id,
- generate_credential_id,
- generate_debug_session_id,
- generate_folder_id,
- generate_id,
- generate_org_id,
- generate_step_id,
- generate_task_id,
- generate_task_v2_id,
- generate_thought_id,
- generate_totp_code_id,
- generate_user_id,
- generate_workflow_id,
- generate_workflow_run_block_id,
- generate_workflow_run_id,
-)
-
-
-class TestConstants:
- """Tests for ID generator constants."""
-
- def test_base_epoch(self):
- """BASE_EPOCH should be June 20, 2022 12:00 AM UTC."""
- assert BASE_EPOCH == 1655683200
-
- def test_version(self):
- """Version should be 0."""
- assert VERSION == 0
-
- def test_bit_allocation(self):
- """Total bits should add up to 64."""
- total_bits = TIMESTAMP_BITS + WORKER_ID_BITS + SEQUENCE_BITS + VERSION_BITS
- assert total_bits == 64
-
- def test_sequence_max(self):
- """SEQUENCE_MAX should be 2^10 - 1 = 1023."""
- assert SEQUENCE_MAX == 1023
-
-
-class TestMaskShift:
- """Tests for the _mask_shift helper function."""
-
- def test_mask_shift_basic(self):
- """Basic mask and shift operation."""
- # value=5 (binary: 101), mask=3 bits, shift=2
- # masked: 5 & 0b111 = 5
- # shifted: 5 << 2 = 20
- result = _mask_shift(5, 3, 2)
- assert result == 20
-
- def test_mask_shift_overflow(self):
- """Value exceeding mask bits should be truncated."""
- # value=15 (binary: 1111), mask=2 bits
- # masked: 15 & 0b11 = 3
- # shifted: 3 << 0 = 3
- result = _mask_shift(15, 2, 0)
- assert result == 3
-
- def test_mask_shift_zero(self):
- """Zero value should return zero."""
- assert _mask_shift(0, 10, 5) == 0
-
- def test_mask_shift_max_bits(self):
- """Test with maximum number of bits."""
- value = (1 << 32) - 1 # Max 32-bit value
- result = _mask_shift(value, 32, 0)
- assert result == value
-
-
-class TestCurrentTime:
- """Tests for time-related functions."""
-
- def test_current_time_is_integer(self):
- """current_time should return an integer."""
- assert isinstance(current_time(), int)
-
- def test_current_time_is_reasonable(self):
- """current_time should be a reasonable Unix timestamp."""
- now = current_time()
- # Should be after BASE_EPOCH
- assert now > BASE_EPOCH
- # Should be within reasonable bounds (before year 2100)
- assert now < 4102444800
-
- def test_current_time_ms_is_integer(self):
- """current_time_ms should return an integer."""
- assert isinstance(current_time_ms(), int)
-
- def test_current_time_ms_is_milliseconds(self):
- """current_time_ms should be roughly 1000x current_time."""
- t = current_time()
- t_ms = current_time_ms()
- # Allow for timing differences
- assert abs(t_ms - t * 1000) < 2000
-
-
-class TestGenerateId:
- """Tests for the generate_id function."""
-
- def test_generate_id_returns_integer(self):
- """generate_id should return an integer."""
- assert isinstance(generate_id(), int)
-
- def test_generate_id_is_positive(self):
- """generate_id should return a positive integer."""
- assert generate_id() > 0
-
- def test_generate_id_is_64_bit(self):
- """generate_id should fit in 64 bits."""
- id_val = generate_id()
- assert id_val < (1 << 64)
-
- def test_generate_id_uniqueness(self):
- """IDs stay unique across a full randomized sequence wrap."""
- ids = [generate_id() for _ in range(SEQUENCE_MAX + 2)]
- assert len(set(ids)) == len(ids)
-
-
-class TestPrefixedIdGenerators:
- """Tests for all prefixed ID generator functions."""
-
- @pytest.mark.parametrize(
- "generator,prefix",
- [
- (generate_workflow_id, WORKFLOW_PREFIX),
- (generate_workflow_run_id, WORKFLOW_RUN_PREFIX),
- (generate_workflow_run_block_id, WORKFLOW_RUN_BLOCK_PREFIX),
- (generate_task_id, TASK_PREFIX),
- (generate_step_id, STEP_PREFIX),
- (generate_artifact_id, ARTIFACT_PREFIX),
- (generate_user_id, USER_PREFIX),
- (generate_org_id, ORG_PREFIX),
- (generate_action_id, ACTION_PREFIX),
- (generate_task_v2_id, TASK_V2_ID),
- (generate_thought_id, THOUGHT_ID),
- (generate_totp_code_id, TOTP_CODE_PREFIX),
- (generate_credential_id, CREDENTIAL_PREFIX),
- (generate_debug_session_id, DEBUG_SESSION_PREFIX),
- (generate_folder_id, FOLDER_PREFIX),
- ],
- )
- def test_id_has_correct_prefix(self, generator, prefix):
- """Generated ID should have the correct prefix."""
- generated_id = generator()
- assert generated_id.startswith(f"{prefix}_")
-
- @pytest.mark.parametrize(
- "generator",
- [
- generate_workflow_id,
- generate_workflow_run_id,
- generate_task_id,
- generate_step_id,
- generate_artifact_id,
- generate_user_id,
- generate_org_id,
- generate_action_id,
- ],
- )
- def test_id_format(self, generator):
- """Generated ID should match expected format: prefix_integer."""
- generated_id = generator()
- assert re.match(r"^[a-z_]+_\d+$", generated_id)
-
- @pytest.mark.parametrize(
- "generator",
- [
- generate_workflow_id,
- generate_task_id,
- generate_org_id,
- ],
- )
- def test_id_uniqueness(self, generator):
- """Multiple calls should generate unique IDs."""
- ids = [generator() for _ in range(100)]
- assert len(set(ids)) == 100
-
- def test_different_generators_produce_different_prefixes(self):
- """Different generators should produce IDs with different prefixes."""
- task_id = generate_task_id()
- step_id = generate_step_id()
- org_id = generate_org_id()
-
- assert task_id.split("_")[0] != step_id.split("_")[0]
- assert task_id.split("_")[0] != org_id.split("_")[0]
- assert step_id.split("_")[0] != org_id.split("_")[0]
-
-
-class TestIdExtraction:
- """Tests for extracting components from generated IDs."""
-
- def test_extract_numeric_part(self):
- """Should be able to extract numeric part from ID."""
- task_id = generate_task_id()
- parts = task_id.split("_")
- numeric_part = int(parts[-1])
- assert numeric_part > 0
-
- def test_numeric_part_is_valid_64bit(self):
- """Numeric part should be a valid 64-bit integer."""
- task_id = generate_task_id()
- numeric_part = int(task_id.split("_")[-1])
- assert numeric_part < (1 << 64)
diff --git a/tests/unit_tests/test_openrouter_integration.py b/tests/unit_tests/test_openrouter_integration.py
deleted file mode 100644
index b4a1112fe..000000000
--- a/tests/unit_tests/test_openrouter_integration.py
+++ /dev/null
@@ -1,189 +0,0 @@
-import importlib
-import json
-import types
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-from skyvern import config
-from skyvern.config import Settings
-from skyvern.forge import app
-from skyvern.forge.forge_app_initializer import start_forge_app
-from skyvern.forge.sdk.api.llm import api_handler_factory, config_registry
-from skyvern.forge.sdk.settings_manager import SettingsManager
-
-
[email protected](scope="module", autouse=True)
-def setup_forge_app():
- start_forge_app()
- yield
-
-
[email protected](autouse=True)
-def _isolate_llm_settings():
- """Every test below mutates three pieces of process-global state --
- SettingsManager's active settings instance, LLMConfigRegistry's
- registered configs, and config_registry's own module-level `settings`
- binding (rebound on every `importlib.reload`, and read directly by
- get_config()'s synthesis fallback) -- without restoring any of them,
- which can leak into (or be leaked into by) unrelated tests depending on
- execution order. Snapshot and restore all three around every test in
- this module.
- """
- previous_settings = SettingsManager.get_settings()
- # Shallow copy is safe: LLMConfig/LLMRouterConfig values are frozen dataclasses.
- previous_configs = dict(config_registry.LLMConfigRegistry._configs)
- previous_module_settings = config_registry.settings
- yield
- SettingsManager.set_settings(previous_settings)
- config_registry.LLMConfigRegistry._configs.clear()
- config_registry.LLMConfigRegistry._configs.update(previous_configs)
- config_registry.settings = previous_module_settings
-
-
-class DummyResponse(dict):
- def __init__(self, content: str):
- super().__init__({"choices": [{"message": {"content": content}}], "usage": {}})
- self.choices = [types.SimpleNamespace(message=types.SimpleNamespace(content=content))]
-
- def model_dump_json(self, indent: int = 2):
- return json.dumps(self, indent=indent)
-
- def model_dump(self):
- return self
-
-
-class DummyArtifactManager:
- async def create_llm_artifact(self, *args, **kwargs):
- return None
-
-
-async def test_openrouter_basic_completion(monkeypatch):
- settings = Settings(
- ENABLE_OPENROUTER=True,
- OPENROUTER_API_KEY="key",
- OPENROUTER_MODEL="test-model",
- LLM_KEY="OPENROUTER",
- )
- SettingsManager.set_settings(settings)
- importlib.reload(config_registry)
-
- monkeypatch.setattr(app, "ARTIFACT_MANAGER", DummyArtifactManager())
-
- async_mock = AsyncMock(return_value=DummyResponse('{"result": "ok"}'))
- monkeypatch.setattr(api_handler_factory.litellm, "acompletion", async_mock)
-
- handler = api_handler_factory.LLMAPIHandlerFactory.get_llm_api_handler("OPENROUTER")
- result = await handler("hi", "test")
- assert result == {"result": "ok"}
- async_mock.assert_called_once()
-
-
-async def test_openrouter_dynamic_model(monkeypatch):
- # config_registry's module-level registration reads skyvern.config.settings
- # directly, while LLMConfigBase.get_missing_env_vars() reads through
- # SettingsManager.get_settings() -- normally the same object, but any test
- # (including siblings in this file) that calls SettingsManager.set_settings()
- # without restoring it breaks that identity. Point both at one new object so
- # this test doesn't depend on which one happened to run last.
- settings = Settings(
- ENABLE_OPENROUTER=True,
- OPENROUTER_API_KEY="key",
- OPENROUTER_MODEL="base-model",
- OPENROUTER_API_BASE="https://openrouter.ai/api/v1",
- LLM_KEY="OPENROUTER",
- )
- SettingsManager.set_settings(settings)
- monkeypatch.setattr(config, "settings", settings)
-
- # Clear existing configs before reload
- config_registry.LLMConfigRegistry._configs.clear()
- importlib.reload(config_registry)
-
- monkeypatch.setattr(app, "ARTIFACT_MANAGER", DummyArtifactManager())
-
- # Mock the AsyncOpenAI client
- async_mock = AsyncMock(return_value=DummyResponse('{"status": "ok"}'))
- mock_client = MagicMock()
- mock_client.chat.completions.create = async_mock
-
- # Patch AsyncOpenAI to return our mock client
- monkeypatch.setattr(api_handler_factory, "AsyncOpenAI", lambda **kwargs: mock_client)
-
- base_handler = api_handler_factory.LLMAPIHandlerFactory.get_llm_api_handler("OPENROUTER")
- override_handler = api_handler_factory.LLMAPIHandlerFactory.get_override_llm_api_handler(
- "openrouter/other-model", default=base_handler
- )
-
- result = await override_handler("hi", "test")
- assert result == {"status": "ok"}
- called_model = async_mock.call_args.kwargs.get("model")
- assert called_model == "other-model"
-
-
-def test_isolate_llm_settings_restores_module_level_settings_binding():
- """Regression: config_registry does `from skyvern.config import settings`, so
- importlib.reload(config_registry) while skyvern.config.settings is monkeypatched
- rebinds config_registry's own module-level `settings` name to that patched
- object. The monkeypatch fixture only restores skyvern.config.settings itself,
- not this separate binding, and get_config()'s synthesis fallback reads it
- directly -- a leak here silently affects any later test's synthesized configs.
- """
- # __wrapped__ recovers the undecorated generator function -- an implementation
- # detail of pytest's fixture wrapper, not public API, but stable since pytest 3.
- gen = _isolate_llm_settings.__wrapped__()
- next(gen) # run the fixture's setup half, snapshotting current state
-
- original_module_settings = config_registry.settings
- fake_settings = Settings(
- ENABLE_OPENROUTER=True,
- OPENROUTER_API_KEY="leaked-key",
- OPENROUTER_MODEL="base-model",
- OPENROUTER_API_BASE="https://openrouter.ai/api/v1",
- LLM_KEY="OPENROUTER",
- )
- with pytest.MonkeyPatch.context() as mp:
- # Registration reads config_registry's module-level settings (patched below);
- # validate_config's get_missing_env_vars() reads through SettingsManager --
- # both must point at the same object or registration itself raises.
- SettingsManager.set_settings(fake_settings)
- mp.setattr(config, "settings", fake_settings)
- importlib.reload(config_registry)
- assert config_registry.settings is fake_settings # sanity: reload really did rebind it
-
- with pytest.raises(StopIteration):
- next(gen) # run the fixture's teardown half
-
- assert config_registry.settings is original_module_settings
-
-
-async def test_openrouter_error_propagation(monkeypatch):
- class DummyAPIError(Exception):
- pass
-
- settings = Settings(
- ENABLE_OPENROUTER=True,
- OPENROUTER_API_KEY="key",
- OPENROUTER_MODEL="test-model",
- LLM_KEY="OPENROUTER",
- )
- SettingsManager.set_settings(settings)
- importlib.reload(config_registry)
-
- monkeypatch.setattr(app, "ARTIFACT_MANAGER", DummyArtifactManager())
-
- async def _raise(*args, **kwargs):
- raise DummyAPIError()
-
- fake_litellm = types.SimpleNamespace(
- acompletion=_raise,
- exceptions=types.SimpleNamespace(APIError=DummyAPIError),
- )
- monkeypatch.setattr(api_handler_factory, "litellm", fake_litellm)
-
- handler = api_handler_factory.LLMAPIHandlerFactory.get_llm_api_handler("OPENROUTER")
- with pytest.raises(api_handler_factory.LLMProviderErrorRetryableTask):
- await handler("hi", "test")
diff --git a/tests/unit_tests/test_schema_validator.py b/tests/unit_tests/test_schema_validator.py
deleted file mode 100644
index da3d027aa..000000000
--- a/tests/unit_tests/test_schema_validator.py
+++ /dev/null
@@ -1,520 +0,0 @@
-from typing import Any
-
-import pytest
-
-from skyvern.forge.sdk.api.llm.schema_validator import (
- fill_missing_fields,
- get_default_value_for_type,
- validate_and_fill_extraction_result,
- validate_data_against_schema,
- validate_schema,
-)
-
-
-class TestSchemaValidator:
- @pytest.fixture
- def medication_schema(self) -> dict[str, Any]:
- """Schema for medication extraction data."""
- return {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "Medication Name": {"type": "string"},
- "NDC": {"type": "string"},
- "quantity": {"type": "string"},
- "facility": {"type": "string"},
- "recoverydate": {"type": ["string", "null"]},
- "isAllocation": {"type": "boolean"},
- "ErrorMessage": {"type": ["string", "null"]},
- },
- "required": [
- "Medication Name",
- "NDC",
- "quantity",
- "facility",
- "recoverydate",
- "isAllocation",
- "ErrorMessage",
- ],
- },
- }
-
- @pytest.fixture
- def complete_medication_data(self) -> list[dict[str, Any]]:
- """Complete medication data with all required fields."""
- return [
- {
- "Medication Name": "ACETAMINOPHEN 1000MG-30ML CHRY LIQ 237ML",
- "NDC": "00904-7481-59",
- "quantity": "0",
- "facility": "CHI-IL",
- "recoverydate": None,
- "isAllocation": False,
- "ErrorMessage": None,
- },
- {
- "Medication Name": "ACETAMINOPHEN CHERRY 160MG/5ML SOL 473ML",
- "NDC": "00904-7014-16",
- "quantity": "100",
- "facility": "CHI-IL",
- "recoverydate": None,
- "isAllocation": False,
- "ErrorMessage": None,
- },
- ]
-
- @pytest.fixture
- def incomplete_medication_data(self) -> list[dict[str, Any]]:
- """Incomplete medication data missing some required fields."""
- return [
- {
- "Medication Name": "ACETAMINOPHEN 1000MG-30ML CHRY LIQ 237ML",
- "NDC": "00904-7481-59",
- "quantity": "0",
- "facility": "CHI-IL",
- # Missing: recoverydate, isAllocation, ErrorMessage
- },
- {
- "Medication Name": "AMOXICILLIN 500MG CAPSULE 500",
- # Missing: NDC, quantity, facility, recoverydate, isAllocation, ErrorMessage
- },
- ]
-
- def test_get_default_value_for_string(self) -> None:
- """Test default value generation for string type."""
- assert get_default_value_for_type("string") is None
-
- def test_get_default_value_for_boolean(self) -> None:
- """Test default value generation for boolean type."""
- assert get_default_value_for_type("boolean") is False
-
- def test_get_default_value_for_array(self) -> None:
- """Test default value generation for array type."""
- assert get_default_value_for_type("array") == []
-
- def test_get_default_value_for_object(self) -> None:
- """Test default value generation for object type."""
- assert get_default_value_for_type("object") == {}
-
- def test_get_default_value_for_null(self) -> None:
- """Test default value generation for null type."""
- assert get_default_value_for_type("null") is None
-
- def test_get_default_value_for_type_list_with_null(self) -> None:
- """Test default value generation for type list containing null."""
- assert get_default_value_for_type(["string", "null"]) is None
- assert get_default_value_for_type(["null", "string"]) is None
-
- def test_get_default_value_for_type_list_all_null(self) -> None:
- """Test default value generation for type list with only null."""
- assert get_default_value_for_type(["null"]) is None
-
- def test_get_default_value_for_uppercase_type(self) -> None:
- """Test default value generation for uppercase type names."""
- assert get_default_value_for_type("STRING") is None
- assert get_default_value_for_type("NUMBER") == 0
- assert get_default_value_for_type("INTEGER") == 0
- assert get_default_value_for_type("BOOLEAN") is False
- assert get_default_value_for_type("ARRAY") == []
- assert get_default_value_for_type("OBJECT") == {}
- assert get_default_value_for_type("NULL") is None
-
- def test_get_default_value_for_mixed_case_type(self) -> None:
- """Test default value generation for mixed case type names."""
- assert get_default_value_for_type("String") is None
- assert get_default_value_for_type("Boolean") is False
- assert get_default_value_for_type(["STRING", "null"]) is None
- assert get_default_value_for_type(["NULL", "STRING"]) is None
-
- def test_fill_missing_fields_complete_data(
- self, medication_schema: dict[str, Any], complete_medication_data: list[dict[str, Any]]
- ) -> None:
- """Test that complete data passes through unchanged."""
- result = fill_missing_fields(complete_medication_data, medication_schema)
- assert result == complete_medication_data
-
- def test_fill_missing_fields_incomplete_data(
- self, medication_schema: dict[str, Any], incomplete_medication_data: list[dict[str, Any]]
- ) -> None:
- """Test that missing required fields are filled with defaults."""
- result = fill_missing_fields(incomplete_medication_data, medication_schema)
-
- # First item should have missing fields filled
- assert result[0]["Medication Name"] == "ACETAMINOPHEN 1000MG-30ML CHRY LIQ 237ML"
- assert result[0]["NDC"] == "00904-7481-59"
- assert result[0]["quantity"] == "0"
- assert result[0]["facility"] == "CHI-IL"
- assert result[0]["recoverydate"] is None # Default for ["string", "null"]
- assert result[0]["isAllocation"] is False # Default for boolean
- assert result[0]["ErrorMessage"] is None # Default for ["string", "null"]
-
- # Second item should have all missing fields filled
- assert result[1]["Medication Name"] == "AMOXICILLIN 500MG CAPSULE 500"
- assert result[1]["NDC"] is None # Default for string
- assert result[1]["quantity"] is None # Default for string
- assert result[1]["facility"] is None # Default for string
- assert result[1]["recoverydate"] is None # Default for ["string", "null"]
- assert result[1]["isAllocation"] is False # Default for boolean
- assert result[1]["ErrorMessage"] is None # Default for ["string", "null"]
-
- def test_fill_missing_fields_with_error_message(self, medication_schema: dict[str, Any]) -> None:
- """Test filling fields when ErrorMessage has a value."""
- data = [
- {
- "Medication Name": "TEST MEDICATION",
- "NDC": "12345-678-90",
- "quantity": "50",
- "facility": "TEST-FACILITY",
- "recoverydate": "2024-01-01",
- "isAllocation": True,
- "ErrorMessage": "Some error occurred",
- }
- ]
-
- result = fill_missing_fields(data, medication_schema)
- assert result[0]["ErrorMessage"] == "Some error occurred"
-
- def test_fill_missing_fields_empty_array(self, medication_schema: dict[str, Any]) -> None:
- """Test handling of empty array."""
- result = fill_missing_fields([], medication_schema)
- assert result == []
-
- def test_fill_missing_fields_invalid_data_type(self, medication_schema: dict[str, Any]) -> None:
- """Test handling when data is not an array."""
- # When data is not a list, it should be converted to empty array
- result = fill_missing_fields("not an array", medication_schema)
- assert result == []
-
- def test_fill_missing_fields_nested_object_missing_fields(self, medication_schema: dict[str, Any]) -> None:
- """Test that nested objects have missing fields filled."""
- data = [
- {
- "Medication Name": "TEST MEDICATION",
- # All other fields missing
- }
- ]
-
- result = fill_missing_fields(data, medication_schema)
- assert len(result) == 1
- assert "NDC" in result[0]
- assert "quantity" in result[0]
- assert "facility" in result[0]
- assert "recoverydate" in result[0]
- assert "isAllocation" in result[0]
- assert "ErrorMessage" in result[0]
-
- def test_validate_and_fill_extraction_result_with_schema(
- self, medication_schema: dict[str, Any], incomplete_medication_data: list[dict[str, Any]]
- ) -> None:
- """Test validate_and_fill_extraction_result with medication schema."""
- result = validate_and_fill_extraction_result(incomplete_medication_data, medication_schema)
-
- # Verify all required fields are present in all items
- for item in result:
- assert "Medication Name" in item
- assert "NDC" in item
- assert "quantity" in item
- assert "facility" in item
- assert "recoverydate" in item
- assert "isAllocation" in item
- assert "ErrorMessage" in item
-
- def test_validate_and_fill_extraction_result_no_schema(self) -> None:
- """Test that data passes through unchanged when no schema is provided."""
- data = {"some": "data"}
- result = validate_and_fill_extraction_result(data, None)
- assert result == data
-
- def test_validate_and_fill_extraction_result_with_exception(self, medication_schema: dict[str, Any]) -> None:
- """Test that original data is returned if validation fails."""
- # This should not raise an exception, but return original data
- invalid_data = "not a valid structure"
- result = validate_and_fill_extraction_result(invalid_data, medication_schema)
- # Should return empty array since invalid_data gets converted
- assert result == []
-
- def test_fill_missing_fields_preserves_existing_values(self, medication_schema: dict[str, Any]) -> None:
- """Test that existing values are preserved and not overwritten."""
- data = [
- {
- "Medication Name": "EXISTING NAME",
- "NDC": "EXISTING-NDC",
- "quantity": "999",
- "facility": "EXISTING-FACILITY",
- "recoverydate": "2024-12-31",
- "isAllocation": True,
- "ErrorMessage": "Existing error",
- }
- ]
-
- result = fill_missing_fields(data, medication_schema)
-
- # All original values should be preserved
- assert result[0]["Medication Name"] == "EXISTING NAME"
- assert result[0]["NDC"] == "EXISTING-NDC"
- assert result[0]["quantity"] == "999"
- assert result[0]["facility"] == "EXISTING-FACILITY"
- assert result[0]["recoverydate"] == "2024-12-31"
- assert result[0]["isAllocation"] is True
- assert result[0]["ErrorMessage"] == "Existing error"
-
- def test_fill_missing_fields_nullable_object_with_null(self) -> None:
- """Test handling of nullable object type when data is null."""
- schema = {
- "type": ["object", "null"],
- "properties": {
- "name": {"type": "string"},
- "age": {"type": "integer"},
- },
- "required": ["name", "age"],
- }
-
- # When data is null, it should remain null (valid for nullable type)
- result = fill_missing_fields(None, schema)
- assert result is None
-
- def test_fill_missing_fields_nullable_object_with_object(self) -> None:
- """Test handling of nullable object type when data is an object with missing fields."""
- schema = {
- "type": ["object", "null"],
- "properties": {
- "name": {"type": "string"},
- "age": {"type": "integer"},
- },
- "required": ["name", "age"],
- }
-
- # When data is an object (not null), missing required fields should be filled
- data = {"name": "John"} # Missing 'age'
- result = fill_missing_fields(data, schema)
-
- # With the fix, missing required fields should be filled
- assert result == {"name": "John", "age": 0}
- assert "name" in result
- assert "age" in result
-
- def test_fill_missing_fields_nullable_array_with_null(self) -> None:
- """Test handling of nullable array type when data is null."""
- schema = {
- "type": ["array", "null"],
- "items": {
- "type": "object",
- "properties": {
- "id": {"type": "string"},
- },
- "required": ["id"],
- },
- }
-
- # When data is null, it should remain null
- result = fill_missing_fields(None, schema)
- assert result is None
-
- def test_fill_missing_fields_nullable_array_with_array(self) -> None:
- """Test handling of nullable array type when data is an array."""
- schema = {
- "type": ["array", "null"],
- "items": {
- "type": "object",
- "properties": {
- "id": {"type": "string"},
- "name": {"type": "string"},
- },
- "required": ["id", "name"],
- },
- }
-
- # When data is an array (not null), items should be validated
- data = [{"id": "1"}] # Missing 'name'
- result = fill_missing_fields(data, schema)
-
- # With the fix, missing fields in array items should be filled
- assert len(result) == 1
- assert result[0] == {"id": "1", "name": None}
- assert "id" in result[0]
- assert "name" in result[0]
-
- def test_validate_schema_valid(self) -> None:
- """Test that valid schemas return True."""
- valid_schema = {
- "type": "object",
- "properties": {
- "name": {"type": "string"},
- "age": {"type": "integer"},
- },
- "required": ["name"],
- }
- assert validate_schema(valid_schema) is True
-
- def test_validate_schema_invalid(self) -> None:
- """Test that invalid schemas return False."""
- invalid_schema = {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "minLength": "not_a_number", # Should be a number
- }
- },
- }
- # Should return False for invalid schema
- assert validate_schema(invalid_schema) is False
-
- def test_validate_schema_none(self) -> None:
- """Test that None schema is considered valid."""
- assert validate_schema(None) is True
-
- def test_validate_schema_string(self) -> None:
- """Test that string schema is considered valid (permissive)."""
- assert validate_schema("some_string") is True
-
- def test_validate_schema_list(self) -> None:
- """Test that list schema is considered valid (permissive)."""
- assert validate_schema([]) is True
-
- def test_validate_data_against_schema_valid(self) -> None:
- """Test validation of valid data against schema."""
- schema = {
- "type": "object",
- "properties": {
- "name": {"type": "string"},
- "age": {"type": "integer"},
- },
- "required": ["name", "age"],
- }
- data = {"name": "John", "age": 30}
- errors = validate_data_against_schema(data, schema)
- assert errors == []
-
- def test_validate_data_against_schema_missing_required(self) -> None:
- """Test validation when required fields are missing."""
- schema = {
- "type": "object",
- "properties": {
- "name": {"type": "string"},
- "age": {"type": "integer"},
- },
- "required": ["name", "age"],
- }
- data = {"name": "John"} # Missing 'age'
- errors = validate_data_against_schema(data, schema)
- assert len(errors) > 0
- assert any("age" in error for error in errors)
-
- def test_validate_data_against_schema_wrong_type(self) -> None:
- """Test validation when data has wrong type."""
- schema = {
- "type": "object",
- "properties": {
- "name": {"type": "string"},
- "age": {"type": "integer"},
- },
- }
- data = {"name": "John", "age": "thirty"} # age should be integer
- errors = validate_data_against_schema(data, schema)
- assert len(errors) > 0
- assert any("age" in error for error in errors)
-
- def test_validate_data_against_schema_array(self) -> None:
- """Test validation of array data."""
- schema = {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "id": {"type": "string"},
- },
- "required": ["id"],
- },
- }
- data = [{"id": "1"}, {"id": "2"}]
- errors = validate_data_against_schema(data, schema)
- assert errors == []
-
- def test_validate_and_fill_with_jsonschema_validation(self, medication_schema: dict[str, Any]) -> None:
- """Test that validate_and_fill uses jsonschema for validation."""
- # Data with all required fields filled correctly
- data = [
- {
- "Medication Name": "TEST MED",
- "NDC": "12345",
- "quantity": "10",
- "facility": "TEST",
- "recoverydate": None,
- "isAllocation": False,
- "ErrorMessage": None,
- }
- ]
-
- result = validate_and_fill_extraction_result(data, medication_schema)
- assert result == data
-
- def test_validate_and_fill_with_invalid_schema(self) -> None:
- """Test that validate_and_fill returns data as-is for invalid schemas."""
- # Create a schema that will fail Draft202012Validator.check_schema
- invalid_schema = {
- "type": "object",
- "properties": {
- "name": {
- "type": "string",
- "minLength": "not_a_number", # Should be a number
- }
- },
- }
-
- data = {"name": "test"}
- # Should return data as-is without transformations when schema is invalid
- result = validate_and_fill_extraction_result(data, invalid_schema)
- assert result == data
-
- def test_filter_invalid_array_items_with_string(self, medication_schema: dict[str, Any]) -> None:
- """Test that array items created from invalid data (strings) are filtered out."""
- # Simulate LLM response with a string mixed in the array
- data = [
- {
- "Medication Name": "ACETAMINOPHEN 500MG",
- "NDC": "12345-678-90",
- "quantity": "100",
- "facility": "TEST-FACILITY",
- "recoverydate": None,
- "isAllocation": False,
- "ErrorMessage": None,
- },
- "This is an invalid string that should be filtered out",
- {
- "Medication Name": "IBUPROFEN 200MG",
- "NDC": "98765-432-10",
- "quantity": "50",
- "facility": "TEST-FACILITY",
- "recoverydate": "2024-01-01",
- "isAllocation": True,
- "ErrorMessage": None,
- },
- ]
-
- result = validate_and_fill_extraction_result(data, medication_schema)
-
- # Should have only 2 valid records (the string should be filtered out)
- assert len(result) == 2
- assert result[0]["Medication Name"] == "ACETAMINOPHEN 500MG"
- assert result[1]["Medication Name"] == "IBUPROFEN 200MG"
-
- def test_filter_invalid_array_items_preserves_valid_defaults(self, medication_schema: dict[str, Any]) -> None:
- """Test that records with some valid data are preserved even if some fields are defaults."""
- data = [
- {
- "Medication Name": "VALID MEDICATION",
- "NDC": "12345-678-90",
- # Missing other required fields - should be filled with defaults but NOT filtered
- }
- ]
-
- result = validate_and_fill_extraction_result(data, medication_schema)
-
- # Should preserve the record because it has meaningful data
- assert len(result) == 1
- assert result[0]["Medication Name"] == "VALID MEDICATION"
- assert result[0]["NDC"] == "12345-678-90"
- assert result[0]["quantity"] is None # Filled with default
- assert result[0]["facility"] is None # Filled with default
diff --git a/tests/unit_tests/test_streaming_screencast.py b/tests/unit_tests/test_streaming_screencast.py
deleted file mode 100644
index 3df3f451d..000000000
--- a/tests/unit_tests/test_streaming_screencast.py
+++ /dev/null
@@ -1,726 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import contextlib
-from collections.abc import Callable
-from types import SimpleNamespace
-from unittest.mock import ANY, AsyncMock, Mock
-
-import pytest
-from fastapi import WebSocketDisconnect
-
-from skyvern.forge.sdk.encrypt.base import TokenDecryptionError
-from tests.unit.scoped_asyncio import ScopedAsyncio
-from tests.unit_tests._stub_streaming import import_with_stubs
-
-screencast = import_with_stubs(
- "skyvern.forge.sdk.routes.streaming.screencast",
- extra_stubs=["skyvern.forge.sdk.routes.streaming.screenshot"],
-)
-
-
-def _make_app(browser_manager=None, persistent_sessions_manager=None):
- """Build a fake app namespace to replace screencast.app (an AppHolder proxy)."""
- return SimpleNamespace(
- BROWSER_MANAGER=browser_manager or SimpleNamespace(),
- PERSISTENT_SESSIONS_MANAGER=persistent_sessions_manager or SimpleNamespace(),
- )
-
-
-async def test_resolve_browser_state_for_workflow_run(monkeypatch: pytest.MonkeyPatch) -> None:
- expected_state = object()
- fake_app = _make_app(
- browser_manager=SimpleNamespace(get_for_workflow_run=Mock(return_value=expected_state), get_for_task=Mock()),
- persistent_sessions_manager=SimpleNamespace(get_observer_browser_state=AsyncMock()),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- result = await screencast._resolve_browser_state("wr_123", "workflow_run")
-
- assert result is expected_state
- fake_app.BROWSER_MANAGER.get_for_workflow_run.assert_called_once_with("wr_123")
- fake_app.BROWSER_MANAGER.get_for_task.assert_not_called()
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.assert_not_awaited()
-
-
-async def test_resolve_browser_state_for_task(monkeypatch: pytest.MonkeyPatch) -> None:
- expected_state = object()
- fake_app = _make_app(
- browser_manager=SimpleNamespace(get_for_workflow_run=Mock(), get_for_task=Mock(return_value=expected_state)),
- persistent_sessions_manager=SimpleNamespace(get_observer_browser_state=AsyncMock()),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- result = await screencast._resolve_browser_state("task_123", "task", workflow_run_id="wr_123")
-
- assert result is expected_state
- fake_app.BROWSER_MANAGER.get_for_task.assert_called_once_with("task_123", "wr_123")
- fake_app.BROWSER_MANAGER.get_for_workflow_run.assert_not_called()
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.assert_not_awaited()
-
-
-async def test_resolve_browser_state_for_browser_session(monkeypatch: pytest.MonkeyPatch) -> None:
- expected_state = object()
- fake_app = _make_app(
- browser_manager=SimpleNamespace(get_for_workflow_run=Mock(), get_for_task=Mock()),
- persistent_sessions_manager=SimpleNamespace(get_observer_browser_state=AsyncMock(return_value=expected_state)),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- result = await screencast._resolve_browser_state("bs_123", "browser_session", organization_id="o_123")
-
- assert result is expected_state
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.assert_awaited_once_with("bs_123", "o_123")
- fake_app.BROWSER_MANAGER.get_for_workflow_run.assert_not_called()
- fake_app.BROWSER_MANAGER.get_for_task.assert_not_called()
-
-
-async def test_resolve_browser_state_unknown_entity_type(monkeypatch: pytest.MonkeyPatch) -> None:
- fake_app = _make_app(
- browser_manager=SimpleNamespace(get_for_workflow_run=Mock(), get_for_task=Mock()),
- persistent_sessions_manager=SimpleNamespace(get_observer_browser_state=AsyncMock()),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- result = await screencast._resolve_browser_state("id_123", "unknown")
-
- assert result is None
- fake_app.BROWSER_MANAGER.get_for_workflow_run.assert_not_called()
- fake_app.BROWSER_MANAGER.get_for_task.assert_not_called()
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.assert_not_awaited()
-
-
-async def test_wait_for_browser_state_returns_when_working_page_is_available(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- browser_state = SimpleNamespace(get_working_page=AsyncMock(return_value=object()))
- resolve_mock = AsyncMock(return_value=browser_state)
- sleep_mock = AsyncMock()
- monkeypatch.setattr(screencast, "_resolve_browser_state", resolve_mock)
- monkeypatch.setattr(screencast, "asyncio", SimpleNamespace(sleep=sleep_mock))
-
- result = await screencast.wait_for_browser_state("wr_123", "workflow_run", timeout=1, poll_interval=0.1)
-
- assert result is browser_state
- resolve_mock.assert_awaited_once_with("wr_123", "workflow_run", None, organization_id=None)
- browser_state.get_working_page.assert_awaited_once()
- sleep_mock.assert_not_awaited()
-
-
-async def test_wait_for_browser_state_returns_none_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
- browser_state = SimpleNamespace(get_working_page=AsyncMock(return_value=None))
- resolve_mock = AsyncMock(return_value=browser_state)
- sleep_mock = AsyncMock()
- monkeypatch.setattr(screencast, "_resolve_browser_state", resolve_mock)
- monkeypatch.setattr(screencast, "asyncio", ScopedAsyncio(sleep=sleep_mock))
-
- result = await screencast.wait_for_browser_state(
- "wr_123",
- "workflow_run",
- timeout=0.3,
- poll_interval=0.1,
- )
-
- assert result is None
- assert resolve_mock.await_count == 3
- assert browser_state.get_working_page.await_count == 3
-
-
-async def test_wait_for_browser_state_gives_up_when_the_org_token_cannot_be_decrypted(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The candidate key set is fixed for the process, so every remaining poll would pay a browser
- attach to fail identically. SKY-15074 burned 480 attaches per websocket that way."""
- resolve_mock = AsyncMock(side_effect=TokenDecryptionError("Failed to decrypt token"))
- sleep_mock = AsyncMock()
- monkeypatch.setattr(screencast, "_resolve_browser_state", resolve_mock)
- monkeypatch.setattr(screencast, "asyncio", ScopedAsyncio(sleep=sleep_mock))
-
- result = await screencast.wait_for_browser_state(
- "pbs_1",
- "browser_session",
- timeout=0.3,
- poll_interval=0.1,
- organization_id="o_1",
- )
-
- assert result is None
- assert resolve_mock.await_count == 1
- sleep_mock.assert_not_awaited()
-
-
- ("entity_id", "entity_type", "kwargs"),
- [
- ("wr_1", "workflow_run", {}),
- ("tsk_1", "task", {"workflow_run_id": "wr_1"}),
- ],
-)
-async def test_a_run_without_in_process_state_never_adopts_the_session(
- monkeypatch: pytest.MonkeyPatch, entity_id: str, entity_type: str, kwargs: dict
-) -> None:
- """A run's frames come from the worker that drives it, so the API process resolves a run only
- against its own manager. Reaching into the session instead would adopt a browser the worker is
- driving — and would miss anyway, since a task inside a workflow leases under the run's id."""
- fake_app = _make_app(
- browser_manager=SimpleNamespace(
- get_for_workflow_run=Mock(return_value=None), get_for_task=Mock(return_value=None)
- ),
- persistent_sessions_manager=SimpleNamespace(
- get_session_by_runnable_id=AsyncMock(),
- get_browser_state=AsyncMock(),
- get_observer_browser_state=AsyncMock(),
- ),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- assert await screencast._resolve_browser_state(entity_id, entity_type, organization_id="o_1", **kwargs) is None
-
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_session_by_runnable_id.assert_not_awaited()
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_browser_state.assert_not_awaited()
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.assert_not_awaited()
-
-
-async def test_waiting_out_a_session_holds_one_connection_and_gives_it_back(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Each resolve mints its own connection, so re-resolving per poll would leave one adopted
- browser per tick behind."""
- browser_state = SimpleNamespace(get_working_page=AsyncMock(return_value=None))
- release = AsyncMock()
- fake_app = _make_app(
- persistent_sessions_manager=SimpleNamespace(
- get_observer_browser_state=AsyncMock(return_value=browser_state),
- release_observer_browser_state=release,
- ),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
- monkeypatch.setattr(screencast, "asyncio", ScopedAsyncio(sleep=AsyncMock()))
-
- result = await screencast.wait_for_browser_state(
- "bs_123", "browser_session", organization_id="o_1", timeout=0.3, poll_interval=0.1
- )
-
- assert result is None
- assert fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.await_count == 1
- assert browser_state.get_working_page.await_count == 3
- release.assert_awaited_once_with("bs_123", browser_state)
-
-
-async def test_following_the_active_page_does_not_reconnect(monkeypatch: pytest.MonkeyPatch) -> None:
- page = object()
- browser_state = SimpleNamespace(get_working_page=AsyncMock(return_value=page))
- fake_app = _make_app(
- persistent_sessions_manager=SimpleNamespace(get_observer_browser_state=AsyncMock()),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- result = await screencast._resolve_working_page(browser_state, "bs_123", "browser_session", organization_id="o_1")
-
- assert result is page
- fake_app.PERSISTENT_SESSIONS_MANAGER.get_observer_browser_state.assert_not_awaited()
-
-
-async def test_a_run_state_is_not_the_viewers_to_release(monkeypatch: pytest.MonkeyPatch) -> None:
- release = AsyncMock()
- fake_app = _make_app(
- persistent_sessions_manager=SimpleNamespace(release_observer_browser_state=release),
- )
- monkeypatch.setattr(screencast, "app", fake_app)
-
- await screencast.release_browser_state(SimpleNamespace(), "workflow_run", "wr_1")
-
- release.assert_not_awaited()
-
-
-class _FakeCdpSession:
- def __init__(self) -> None:
- self.handlers: dict[str, object] = {}
- self.sent: list[tuple[str, dict]] = []
- self.detached = False
- self.fail_methods: set[str] = set()
- self.fail_after_calls: dict[str, int] = {}
-
- def on(self, event: str, handler: object) -> None:
- self.handlers[event] = handler
-
- async def send(self, method: str, params: dict | None = None) -> dict:
- self.sent.append((method, params or {}))
- if method in self.fail_methods and self.methods_sent().count(method) > self.fail_after_calls.get(method, 0):
- raise RuntimeError(f"{method} refused")
- if method == "Page.captureScreenshot":
- return {"data": "primed"}
- return {}
-
- async def detach(self) -> None:
- self.detached = True
-
- def methods_sent(self) -> list[str]:
- return [method for method, _ in self.sent]
-
-
-class _FakePage:
- def __init__(self, session: _FakeCdpSession) -> None:
- self.context = SimpleNamespace(new_cdp_session=AsyncMock(return_value=session))
- self.url = "https://example.test/"
- self.viewport_size = {"width": 800, "height": 600}
-
-
-def _connected_websocket(send_json: object) -> SimpleNamespace:
- """A real WebSocket is readable, and the screencast loop reads it to notice a client disconnect."""
-
- async def _receive() -> dict:
- await asyncio.Event().wait()
- raise AssertionError("unreachable")
-
- return SimpleNamespace(send_json=send_json, receive=_receive)
-
-
-async def _wait_for(predicate: Callable[[], bool]) -> bool:
- for _ in range(500):
- if predicate():
- return True
- await asyncio.sleep(0.01)
- return False
-
-
-async def test_forwarded_frame_is_acked_and_records_forward_latency(monkeypatch: pytest.MonkeyPatch) -> None:
- session = _FakeCdpSession()
- page = _FakePage(session)
- monkeypatch.setattr(screencast, "_resolve_working_page", AsyncMock(return_value=page))
- forward_hist, queue_hist, send_hist = Mock(), Mock(), Mock()
- monkeypatch.setattr(screencast, "_frame_forward_seconds", forward_hist)
- monkeypatch.setattr(screencast, "_frame_queue_seconds", queue_hist)
- monkeypatch.setattr(screencast, "_frame_send_seconds", send_hist)
-
- sent: list[dict] = []
-
- async def _send_json(payload: dict) -> None:
- sent.append(payload)
- if len(sent) == 2:
- raise RuntimeError("client gone")
-
- websocket = _connected_websocket(_send_json)
-
- async def _never_finalized() -> bool:
- return False
-
- loop_task = asyncio.create_task(
- screencast.start_screencast_loop(websocket, object(), "pbs_1", "browser_session", _never_finalized)
- )
- for _ in range(100):
- if "Page.screencastFrame" in session.handlers:
- break
- await asyncio.sleep(0.01)
- session.handlers["Page.screencastFrame"](
- {"data": "AAAA", "sessionId": 7, "metadata": {"deviceWidth": 640, "deviceHeight": 480}}
- )
- await asyncio.wait_for(loop_task, timeout=5)
-
- assert [m["screenshot"] for m in sent] == ["primed", "AAAA"]
- assert sent[1]["viewport_width"] == 640 and sent[1]["viewport_height"] == 480
- assert ("Page.screencastFrameAck", {"sessionId": 7}) in session.sent
- assert queue_hist.record.call_count == 2
- assert forward_hist.record.call_count == 1 and send_hist.record.call_count == 1
- value, attributes = forward_hist.record.call_args.args
- assert value >= 0 and attributes == {"entity_type": "browser_session"}
-
-
-async def test_client_disconnect_is_raised_so_the_caller_does_not_write_a_final_status(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- session = _FakeCdpSession()
- monkeypatch.setattr(screencast, "_resolve_working_page", AsyncMock(return_value=_FakePage(session)))
- websocket = SimpleNamespace(
- send_json=AsyncMock(),
- receive=AsyncMock(return_value={"type": "websocket.disconnect", "code": 1006}),
- )
-
- async def _never_finalized() -> bool:
- return False
-
- with pytest.raises(WebSocketDisconnect):
- await asyncio.wait_for(
- screencast.start_screencast_loop(websocket, object(), "pbs_1", "browser_session", _never_finalized),
- timeout=5,
- )
- assert session.detached
-
-
-async def test_evicted_frame_records_queue_dwell(monkeypatch: pytest.MonkeyPatch) -> None:
- session = _FakeCdpSession()
- page = _FakePage(session)
- monkeypatch.setattr(screencast, "_resolve_working_page", AsyncMock(return_value=page))
- queue_hist, evicted = Mock(), Mock()
- monkeypatch.setattr(screencast, "_frame_queue_seconds", queue_hist)
- monkeypatch.setattr(screencast, "_frames_evicted", evicted)
-
- first_send_started = asyncio.Event()
- release_first_send = asyncio.Event()
- sent: list[dict] = []
-
- async def _send_json(payload: dict) -> None:
- sent.append(payload)
- if payload["screenshot"] == "primed":
- first_send_started.set()
- await release_first_send.wait()
- elif payload["screenshot"] == "frame-3":
- raise RuntimeError("client gone")
-
- websocket = _connected_websocket(_send_json)
-
- async def _never_finalized() -> bool:
- return False
-
- loop_task = asyncio.create_task(
- screencast.start_screencast_loop(websocket, object(), "pbs_1", "browser_session", _never_finalized)
- )
- for _ in range(100):
- if "Page.screencastFrame" in session.handlers:
- break
- await asyncio.sleep(0.01)
- await asyncio.wait_for(first_send_started.wait(), timeout=5)
-
- try:
- for data in ("frame-1", "frame-2", "frame-3"):
- session.handlers["Page.screencastFrame"]({"data": data, "sessionId": 7, "metadata": {}})
- await asyncio.sleep(0)
-
- for _ in range(100):
- if evicted.add.called:
- break
- await asyncio.sleep(0.01)
-
- assert evicted.add.call_count == 1
- # The forwarding loop has dequeued only the primed frame, so the second sample
- # can only come from the oldest queued frame that was evicted.
- assert queue_hist.record.call_count == 2
- value, attributes = queue_hist.record.call_args.args
- assert value >= 0 and attributes == {"entity_type": "browser_session"}
- finally:
- release_first_send.set()
- await asyncio.wait_for(loop_task, timeout=5)
-
- assert [payload["screenshot"] for payload in sent] == ["primed", "frame-2", "frame-3"]
-
-
-async def test_a_page_that_cannot_be_attached_does_not_kill_the_running_stream(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- current_session = _FakeCdpSession()
- current_page = _FakePage(current_session)
- next_session = _FakeCdpSession()
- next_page = _FakePage(next_session)
- attach_fails = True
-
- async def _new_cdp_session(_page: object) -> _FakeCdpSession:
- if attach_fails:
- raise RuntimeError("Target closed")
- return next_session
-
- next_page.context.new_cdp_session = AsyncMock(side_effect=_new_cdp_session)
- monkeypatch.setattr(screencast, "ACTIVE_PAGE_POLL_INTERVAL", 0.01)
- # Cap the backoff too: a slow runner could otherwise spend long enough failing to attach
- # that the poll interval grows past this test's own wait budget.
- monkeypatch.setattr(screencast, "ACTIVE_PAGE_MAX_POLL_INTERVAL", 0.05)
-
- pages = iter([current_page])
-
- async def _resolve_working_page(*_args: object, **_kwargs: object) -> object:
- return next(pages, next_page)
-
- monkeypatch.setattr(screencast, "_resolve_working_page", _resolve_working_page)
-
- sent: list[dict] = []
-
- async def _send_json(payload: dict) -> None:
- sent.append(payload)
- if payload["screenshot"] == "frame-from-next-page":
- raise RuntimeError("client gone")
-
- websocket = _connected_websocket(_send_json)
-
- async def _never_finalized() -> bool:
- return False
-
- loop_task = asyncio.create_task(
- screencast.start_screencast_loop(websocket, object(), "pbs_1", "browser_session", _never_finalized)
- )
- assert await _wait_for(lambda: bool(next_page.context.new_cdp_session.await_count))
-
- assert current_session.detached is False
- assert "Page.stopScreencast" not in current_session.methods_sent()
- current_session.handlers["Page.screencastFrame"](
- {"data": "frame-from-current-page", "sessionId": 7, "metadata": {}}
- )
- assert await _wait_for(lambda: any(payload["screenshot"] == "frame-from-current-page" for payload in sent))
-
- attach_fails = False
- assert await _wait_for(lambda: "Page.startScreencast" in next_session.methods_sent())
- assert await _wait_for(lambda: current_session.detached)
- next_session.handlers["Page.screencastFrame"]({"data": "frame-from-next-page", "sessionId": 9, "metadata": {}})
- await asyncio.wait_for(loop_task, timeout=5)
-
- assert [payload["screenshot"] for payload in sent] == [
- "primed",
- "frame-from-current-page",
- "primed",
- "frame-from-next-page",
- ]
-
-
-class _FramesDuringStartSession(_FakeCdpSession):
- """Emits a frame before Page.startScreencast returns, i.e. before the loop can adopt it."""
-
- async def send(self, method: str, params: dict | None = None) -> dict:
- result = await super().send(method, params)
- if method == "Page.startScreencast":
- self.handlers["Page.screencastFrame"]({"data": "mid-swap", "sessionId": 11, "metadata": {}})
- await asyncio.sleep(0)
- return result
-
-
-async def test_a_frame_that_lands_mid_swap_is_still_acked(monkeypatch: pytest.MonkeyPatch) -> None:
- session = _FramesDuringStartSession()
- page = _FakePage(session)
- monkeypatch.setattr(screencast, "_resolve_working_page", AsyncMock(return_value=page))
-
- sent: list[dict] = []
-
- async def _send_json(payload: dict) -> None:
- sent.append(payload)
- raise RuntimeError("client gone")
-
- async def _never_finalized() -> bool:
- return False
-
- await asyncio.wait_for(
- screencast.start_screencast_loop(
- _connected_websocket(_send_json), object(), "pbs_1", "browser_session", _never_finalized
- ),
- timeout=5,
- )
-
- # Chrome stops producing frames for a session whose frames go unacked, so the ack has to happen
- # even though the frame arrived too early to be forwarded.
- assert ("Page.screencastFrameAck", {"sessionId": 11}) in session.sent
- assert [payload["screenshot"] for payload in sent] == ["primed"]
-
-
-_REAL_SLEEP = asyncio.sleep
-
-
-class _VirtualClock:
- """Instant sleeps over a virtual monotonic clock, recorded per calling task.
-
- Grouping by task keeps the completion poller's one sleep out of the page monitor's sequence.
- """
-
- def __init__(self, stop_after: int) -> None:
- self.by_task: dict[int, list[float]] = {}
- self.now = 0.0
- self._stop_after = stop_after
- self.parked = asyncio.Event()
-
- def monotonic(self) -> float:
- return self.now
-
- async def sleep(self, delay: float) -> None:
- recorded = self.by_task.setdefault(id(asyncio.current_task()), [])
- recorded.append(delay)
- self.now += delay
- if len(recorded) >= self._stop_after:
- self.parked.set()
- await asyncio.Event().wait()
- await _REAL_SLEEP(0)
-
- @property
- def poll_delays(self) -> list[float]:
- return max(self.by_task.values(), key=len, default=[])
-
-
-def _scripted_pages(*script: object):
- """Resolve pages in order, then hold the final entry forever."""
- remaining = list(script)
-
- async def _resolve(*args: object, **kwargs: object) -> object:
- return remaining.pop(0) if len(remaining) > 1 else remaining[0]
-
- return _resolve
-
-
-async def _drive_page_monitor(
- monkeypatch: pytest.MonkeyPatch,
- clock: _VirtualClock,
- *script: object,
- entity_id: str = "pbs_1",
- entity_type: str = "browser_session",
- **loop_kwargs: object,
-) -> asyncio.Task:
- monkeypatch.setattr(screencast, "_resolve_working_page", _scripted_pages(*script))
- monkeypatch.setattr(screencast, "asyncio", ScopedAsyncio(sleep=clock.sleep))
- monkeypatch.setattr(screencast, "time", SimpleNamespace(monotonic=clock.monotonic))
-
- async def _never_finalized() -> bool:
- await asyncio.Event().wait()
- return False
-
- task = asyncio.create_task(
- screencast.start_screencast_loop(
- _connected_websocket(AsyncMock()),
- object(),
- entity_id,
- entity_type,
- _never_finalized,
- **loop_kwargs,
- )
- )
- await asyncio.wait_for(clock.parked.wait(), timeout=5)
- return task
-
-
-async def _stop(task: asyncio.Task) -> None:
- # Cancelling start_screencast_loop mid-wait leaves its child tasks running, so drain them too.
- task.cancel()
- for pending in asyncio.all_tasks() - {asyncio.current_task()}:
- pending.cancel()
- with contextlib.suppress(BaseException):
- await pending
-
-
-def _messages(calls: list, message: str) -> list:
- return [call for call in calls if call.args and call.args[0] == message]
-
-
-async def test_page_poll_holds_the_fast_cadence_then_backs_off_and_clamps(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """Ordinary page-less gaps clear in a few seconds, so the fast cadence is held past them; only a
- wedged viewer reaches the backoff, and it must stop doubling at the ceiling rather than growing."""
- clock = _VirtualClock(stop_after=16)
- task = await _drive_page_monitor(monkeypatch, clock, _FakePage(_FakeCdpSession()), None)
-
- try:
- assert clock.poll_delays == [0.5] * 9 + [1.0, 2.0, 4.0, 8.0, 16.0, 30.0, 30.0]
- finally:
- await _stop(task)
-
-
-async def test_degraded_entry_is_reported_exactly_once(monkeypatch: pytest.MonkeyPatch) -> None:
- """The whole point of the bound: one wedged viewer used to log on every poll."""
- log = Mock()
- monkeypatch.setattr(screencast, "LOG", log)
- clock = _VirtualClock(stop_after=60)
- task = await _drive_page_monitor(
- monkeypatch,
- clock,
- _FakePage(_FakeCdpSession()),
- None,
- entity_id="pbs_1",
- entity_type="browser_session",
- organization_id="o_1",
- )
-
- try:
- entries = _messages(log.warning.call_args_list, "Live view cannot follow the active page; backing off")
- assert len(clock.poll_delays) == 60
- assert len(entries) == 1
- assert entries[0].kwargs["browser_session_id"] == "pbs_1"
- assert entries[0].kwargs["entity_id"] == "pbs_1"
- assert entries[0].kwargs["entity_type"] == "browser_session"
- assert entries[0].kwargs["organization_id"] == "o_1"
- assert entries[0].kwargs["degraded_for_seconds"] == 4.0
- finally:
- await _stop(task)
-
-
-async def test_a_page_appearing_mid_backoff_recovers_and_reports_the_degraded_duration(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- log = Mock()
- monkeypatch.setattr(screencast, "LOG", log)
- clock = _VirtualClock(stop_after=15)
- recovered = _FakePage(_FakeCdpSession())
- task = await _drive_page_monitor(
- monkeypatch,
- clock,
- _FakePage(_FakeCdpSession()),
- *([None] * 12),
- recovered,
- )
-
- try:
- recoveries = _messages(log.info.call_args_list, "Live view is following the active page again")
- assert len(recoveries) == 1
- # Empty from t=0.5 until the page came back at t=19.5, across the 0.5->8.0 backoff.
- assert recoveries[0].kwargs["degraded_for_seconds"] == 19.0
- assert recoveries[0].kwargs["browser_session_id"] == "pbs_1"
- # The screencast re-attached to the page that came back, and the fast cadence resumed.
- assert ("Page.startScreencast", ANY) in recovered.context.new_cdp_session.return_value.sent
- assert clock.poll_delays[13:] == [0.5, 0.5]
- finally:
- await _stop(task)
-
-
-async def test_the_page_monitor_survives_a_long_degraded_stretch(monkeypatch: pytest.MonkeyPatch) -> None:
- """Backing off is not giving up: the viewer stays connected so a page that returns is followed."""
- clock = _VirtualClock(stop_after=200)
- task = await _drive_page_monitor(monkeypatch, clock, _FakePage(_FakeCdpSession()), None)
-
- try:
- assert not task.done()
- assert len(clock.poll_delays) == 200
- assert set(clock.poll_delays[20:]) == {30.0}
- finally:
- await _stop(task)
-
-
-class _UnattachablePage:
- """Resolves fine, but every attempt to open a CDP session on it fails."""
-
- def __init__(self) -> None:
- self.context = SimpleNamespace(new_cdp_session=AsyncMock(side_effect=RuntimeError("cdp session refused")))
- self.url = "https://example.test/"
- self.viewport_size = {"width": 800, "height": 600}
-
-
-async def test_a_page_that_never_attaches_backs_off_like_a_missing_one(monkeypatch: pytest.MonkeyPatch) -> None:
- """A page the viewer cannot attach to is as dead as no page: without this the loop would sit at
- 2 Hz forever on a failing attach, which is the pathology the backoff exists to stop."""
- log = Mock()
- monkeypatch.setattr(screencast, "LOG", log)
- clock = _VirtualClock(stop_after=12)
- task = await _drive_page_monitor(
- monkeypatch,
- clock,
- _FakePage(_FakeCdpSession()),
- _UnattachablePage(),
- )
-
- try:
- assert clock.poll_delays == [0.5] * 9 + [1.0, 2.0, 4.0]
- entries = _messages(log.warning.call_args_list, "Live view cannot follow the active page; backing off")
- assert len(entries) == 1
- finally:
- await _stop(task)
diff --git a/tests/unit_tests/test_streaming_screenshot_local.py b/tests/unit_tests/test_streaming_screenshot_local.py
deleted file mode 100644
index 92f8563dc..000000000
--- a/tests/unit_tests/test_streaming_screenshot_local.py
+++ /dev/null
@@ -1,224 +0,0 @@
-from __future__ import annotations
-
-from types import SimpleNamespace
-from unittest.mock import AsyncMock
-
-import pytest
-
-from tests.unit_tests._stub_streaming import import_with_stubs
-
-screenshot = import_with_stubs("skyvern.forge.sdk.routes.streaming.screenshot")
-
-
-async def test_run_local_screencast_happy_path(monkeypatch: pytest.MonkeyPatch) -> None:
- websocket = object()
- browser_state = object()
- wait_for_running = AsyncMock(return_value=None)
- check_finalized = AsyncMock(return_value=False)
- get_current_status = AsyncMock(return_value="completed")
- wait_for_browser_state_mock = AsyncMock(return_value=browser_state)
- start_screencast_loop_mock = AsyncMock()
- send_status_mock = AsyncMock()
- monkeypatch.setattr(screenshot, "wait_for_browser_state", wait_for_browser_state_mock)
- monkeypatch.setattr(screenshot, "start_screencast_loop", start_screencast_loop_mock)
- monkeypatch.setattr(screenshot, "_send_status", send_status_mock)
-
- await screenshot._run_local_screencast(
- websocket=websocket,
- entity_id="task_123",
- entity_type="task",
- wait_for_running=wait_for_running,
- check_finalized=check_finalized,
- get_current_status=get_current_status,
- organization_id="org_123",
- get_workflow_run_id=lambda: "wr_123",
- )
-
- wait_for_running.assert_awaited_once()
- wait_for_browser_state_mock.assert_awaited_once_with(
- "task_123", "task", workflow_run_id="wr_123", organization_id="org_123"
- )
- start_screencast_loop_mock.assert_awaited_once_with(
- websocket=websocket,
- browser_state=browser_state,
- entity_id="task_123",
- entity_type="task",
- check_finalized=check_finalized,
- workflow_run_id="wr_123",
- organization_id="org_123",
- )
- get_current_status.assert_awaited_once()
- send_status_mock.assert_awaited_once_with(websocket, "task_id", "task_123", "completed")
-
-
- ("current_status", "expected_status"),
- [
- ("running", "timeout"),
- ("session_expired", "session_expired"),
- ("completed", "completed"),
- ("failed", "failed"),
- ],
-)
-async def test_run_local_screencast_timeout_when_browser_state_not_available(
- monkeypatch: pytest.MonkeyPatch,
- current_status: str,
- expected_status: str,
-) -> None:
- websocket = object()
- wait_for_running = AsyncMock(return_value=None)
- check_finalized = AsyncMock(return_value=False)
- get_current_status = AsyncMock(return_value=current_status)
- wait_for_browser_state_mock = AsyncMock(return_value=None)
- start_screencast_loop_mock = AsyncMock()
- send_status_mock = AsyncMock()
- monkeypatch.setattr(screenshot, "wait_for_browser_state", wait_for_browser_state_mock)
- monkeypatch.setattr(screenshot, "start_screencast_loop", start_screencast_loop_mock)
- monkeypatch.setattr(screenshot, "_send_status", send_status_mock)
-
- await screenshot._run_local_screencast(
- websocket=websocket,
- entity_id="bs_123",
- entity_type="browser_session",
- wait_for_running=wait_for_running,
- check_finalized=check_finalized,
- get_current_status=get_current_status,
- organization_id="org_123",
- )
-
- wait_for_running.assert_awaited_once()
- wait_for_browser_state_mock.assert_awaited_once_with(
- "bs_123",
- "browser_session",
- workflow_run_id=None,
- organization_id="org_123",
- )
- start_screencast_loop_mock.assert_not_awaited()
- get_current_status.assert_awaited_once()
- send_status_mock.assert_awaited_once_with(websocket, "browser_session_id", "bs_123", expected_status)
-
-
-async def test_expired_browser_session_is_distinct_from_stream_launch_timeout(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- websocket = object()
- wait_for_browser_state_mock = AsyncMock()
- send_status_mock = AsyncMock()
- monkeypatch.setattr(
- screenshot,
- "app",
- SimpleNamespace(
- PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(
- get_session=AsyncMock(return_value=SimpleNamespace(status="timeout"))
- )
- ),
- )
- monkeypatch.setattr(screenshot, "wait_for_browser_state", wait_for_browser_state_mock)
- monkeypatch.setattr(screenshot, "_send_status", send_status_mock)
- monkeypatch.setattr(screenshot, "release_browser_state", AsyncMock())
-
- await screenshot._local_screencast_for_browser_session(websocket, "pbs_123", "org_123")
-
- wait_for_browser_state_mock.assert_not_awaited()
- send_status_mock.assert_awaited_once_with(
- websocket,
- "browser_session_id",
- "pbs_123",
- "session_expired",
- )
-
-
-async def test_browser_session_expiring_while_waiting_for_browser_state_is_distinct(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- websocket = object()
- get_session = AsyncMock(
- side_effect=[
- SimpleNamespace(status="running"),
- SimpleNamespace(status="timeout"),
- ]
- )
- send_status_mock = AsyncMock()
- monkeypatch.setattr(
- screenshot,
- "app",
- SimpleNamespace(
- PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(get_session=get_session),
- ),
- )
- monkeypatch.setattr(screenshot, "wait_for_browser_state", AsyncMock(return_value=None))
- monkeypatch.setattr(screenshot, "_send_status", send_status_mock)
- monkeypatch.setattr(screenshot, "release_browser_state", AsyncMock())
-
- await screenshot._local_screencast_for_browser_session(websocket, "pbs_123", "org_123")
-
- send_status_mock.assert_awaited_once_with(
- websocket,
- "browser_session_id",
- "pbs_123",
- "session_expired",
- )
-
-
-async def test_browser_state_timeout_survives_status_refresh_failure(monkeypatch: pytest.MonkeyPatch) -> None:
- websocket = object()
- get_session = AsyncMock(
- side_effect=[
- SimpleNamespace(status="running"),
- RuntimeError("status unavailable"),
- ]
- )
- send_status_mock = AsyncMock()
- monkeypatch.setattr(
- screenshot,
- "app",
- SimpleNamespace(
- PERSISTENT_SESSIONS_MANAGER=SimpleNamespace(get_session=get_session),
- ),
- )
- monkeypatch.setattr(screenshot, "wait_for_browser_state", AsyncMock(return_value=None))
- monkeypatch.setattr(screenshot, "_send_status", send_status_mock)
- monkeypatch.setattr(screenshot, "release_browser_state", AsyncMock())
-
- await screenshot._local_screencast_for_browser_session(websocket, "pbs_123", "org_123")
-
- send_status_mock.assert_awaited_once_with(
- websocket,
- "browser_session_id",
- "pbs_123",
- "timeout",
- )
-
-
- ("entrypoint", "entity_id", "database_attr", "getter"),
- [
- ("_local_screencast_for_task", "tsk_123", "tasks", "get_task"),
- ("_local_screencast_for_workflow_run", "wr_123", "workflow_runs", "get_workflow_run"),
- ],
-)
-async def test_local_screencast_forwards_the_organization(
- monkeypatch: pytest.MonkeyPatch, entrypoint: str, entity_id: str, database_attr: str, getter: str
-) -> None:
- """A browser held out of process is reachable only through an organization-scoped session
- lookup, so an entrypoint that drops the organization streams nothing."""
- finished = SimpleNamespace(status=SimpleNamespace(is_final=lambda: True), organization_id="org_123")
- monkeypatch.setattr(
- screenshot,
- "app",
- SimpleNamespace(
- DATABASE=SimpleNamespace(**{database_attr: SimpleNamespace(**{getter: AsyncMock(return_value=finished)})})
- ),
- )
- run_local_screencast_mock = AsyncMock()
- monkeypatch.setattr(screenshot, "_run_local_screencast", run_local_screencast_mock)
-
- await getattr(screenshot, entrypoint)(object(), entity_id, "org_123")
-
- assert run_local_screencast_mock.await_args.kwargs["organization_id"] == "org_123"
diff --git a/tests/unit_tests/test_string_util.py b/tests/unit_tests/test_string_util.py
deleted file mode 100644
index 26548b3bb..000000000
--- a/tests/unit_tests/test_string_util.py
+++ /dev/null
@@ -1,63 +0,0 @@
-from skyvern.webeye.string_util import remove_whitespace
-
-
-class TestRemoveWhitespace:
- """Tests for the remove_whitespace function."""
-
- def test_remove_multiple_spaces(self):
- """Multiple spaces should be collapsed to single space."""
- assert remove_whitespace("hello world") == "hello world"
-
- def test_remove_tabs(self):
- """Tab characters should be converted to single space."""
- assert remove_whitespace("hello\tworld") == "hello world"
-
- def test_remove_newlines(self):
- """Newline characters should be converted to single space."""
- assert remove_whitespace("hello\nworld") == "hello world"
-
- def test_remove_mixed_whitespace(self):
- """Mixed whitespace (spaces, tabs, newlines) should be collapsed."""
- assert remove_whitespace("hello \t\n world") == "hello world"
-
- def test_leading_trailing_whitespace(self):
- """Leading and trailing whitespace should be collapsed but not removed."""
- assert remove_whitespace(" hello ") == " hello "
-
- def test_empty_string(self):
- """Empty string should return empty string."""
- assert remove_whitespace("") == ""
-
- def test_single_space(self):
- """Single space should remain unchanged."""
- assert remove_whitespace(" ") == " "
-
- def test_no_whitespace(self):
- """String without extra whitespace should remain unchanged."""
- assert remove_whitespace("hello") == "hello"
-
- def test_only_whitespace(self):
- """String of only whitespace should collapse to single space."""
- assert remove_whitespace(" \t\n ") == " "
-
- def test_multiline_text(self):
- """Multiline text should have all whitespace collapsed."""
- input_text = """Hello
- World
- Test"""
- assert remove_whitespace(input_text) == "Hello World Test"
-
- def test_preserves_non_whitespace_special_chars(self):
- """Non-whitespace special characters should be preserved."""
- assert remove_whitespace("hello!@#$%^&*()world") == "hello!@#$%^&*()world"
-
- def test_unicode_text(self):
- """Unicode text with whitespace should work correctly."""
- assert remove_whitespace("你好 世界") == "你好 世界"
-
- def test_carriage_return_not_matched(self):
- """Carriage return is not in the regex pattern, verify behavior."""
- # Note: \r is not in the original regex pattern [ \n\t]+
- # This test documents the current behavior
- result = remove_whitespace("hello\rworld")
- assert result == "hello\rworld"
diff --git a/tests/unit_tests/test_strings.py b/tests/unit_tests/test_strings.py
deleted file mode 100644
index fe58e3c7a..000000000
--- a/tests/unit_tests/test_strings.py
+++ /dev/null
@@ -1,91 +0,0 @@
-"""Tests for string utility functions."""
-
-import string
-
-from skyvern.utils.strings import RANDOM_STRING_POOL, generate_random_string
-
-
-class TestRandomStringPool:
- """Tests for RANDOM_STRING_POOL constant."""
-
- def test_pool_contains_letters(self):
- """Pool should contain all ASCII letters."""
- for char in string.ascii_letters:
- assert char in RANDOM_STRING_POOL
-
- def test_pool_contains_digits(self):
- """Pool should contain all digits."""
- for char in string.digits:
- assert char in RANDOM_STRING_POOL
-
- def test_pool_size(self):
- """Pool should have expected size (26*2 + 10 = 62)."""
- assert len(RANDOM_STRING_POOL) == 62
-
-
-class TestGenerateRandomString:
- """Tests for generate_random_string function."""
-
- def test_default_length(self):
- """Default length should be 5."""
- result = generate_random_string()
- assert len(result) == 5
-
- def test_custom_length(self):
- """Custom length should be respected."""
- for length in [1, 10, 50, 100]:
- result = generate_random_string(length)
- assert len(result) == length
-
- def test_zero_length(self):
- """Zero length should return empty string."""
- result = generate_random_string(0)
- assert result == ""
-
- def test_returns_string(self):
- """Should return a string type."""
- result = generate_random_string()
- assert isinstance(result, str)
-
- def test_only_alphanumeric(self):
- """Result should only contain alphanumeric characters."""
- result = generate_random_string(100)
- for char in result:
- assert char in RANDOM_STRING_POOL
-
- def test_randomness(self):
- """Multiple calls should produce different results (with high probability)."""
- results = [generate_random_string(20) for _ in range(10)]
- # All results should be unique (statistically extremely likely with length 20)
- assert len(set(results)) == 10
-
- def test_distribution(self):
- """Characters should be reasonably distributed."""
- # Generate a long string and check distribution
- result = generate_random_string(10000)
- char_counts = {}
- for char in result:
- char_counts[char] = char_counts.get(char, 0) + 1
-
- # Each character should appear at least once in 10000 characters
- # (statistically extremely likely)
- assert len(char_counts) > 50 # Most of the 62 chars should appear
-
- def test_contains_letters(self):
- """Generated strings should typically contain letters."""
- # With 62 possible chars and length 100, very likely to have letters
- result = generate_random_string(100)
- has_letter = any(c in string.ascii_letters for c in result)
- assert has_letter
-
- def test_contains_digits(self):
- """Generated strings should typically contain digits."""
- # With 62 possible chars and length 100, very likely to have digits
- result = generate_random_string(100)
- has_digit = any(c in string.digits for c in result)
- assert has_digit
-
- def test_large_length(self):
- """Should handle large lengths."""
- result = generate_random_string(10000)
- assert len(result) == 10000
diff --git a/tests/unit_tests/test_token_counter.py b/tests/unit_tests/test_token_counter.py
deleted file mode 100644
index bc6e4486e..000000000
--- a/tests/unit_tests/test_token_counter.py
+++ /dev/null
@@ -1,136 +0,0 @@
-"""Tests for token counter utility."""
-
-from skyvern.utils.token_counter import approx_count_tokens, count_tokens
-
-
-class TestCountTokens:
- """Tests for count_tokens function."""
-
- def test_empty_string(self):
- """Empty string should have 0 tokens."""
- assert count_tokens("") == 0
-
- def test_single_word(self):
- """Single word should return token count."""
- result = count_tokens("hello")
- assert result > 0
- assert isinstance(result, int)
-
- def test_simple_sentence(self):
- """Simple sentence should have reasonable token count."""
- result = count_tokens("Hello, world!")
- assert result > 0
- # "Hello, world!" typically tokenizes to ~4 tokens
- assert result < 10
-
- def test_longer_text(self):
- """Longer text should have more tokens."""
- short = count_tokens("Hi")
- long = count_tokens("This is a much longer sentence with many more words in it.")
- assert long > short
-
- def test_returns_integer(self):
- """Should return an integer."""
- result = count_tokens("test")
- assert isinstance(result, int)
-
- def test_whitespace_only(self):
- """Whitespace should be tokenized."""
- result = count_tokens(" ")
- # Whitespace is typically tokenized
- assert isinstance(result, int)
-
- def test_special_characters(self):
- """Special characters should be tokenized."""
- result = count_tokens("!@#$%^&*()")
- assert result > 0
-
- def test_numbers(self):
- """Numbers should be tokenized."""
- result = count_tokens("12345")
- assert result > 0
-
- def test_unicode(self):
- """Unicode characters should be tokenized."""
- result = count_tokens("你好世界")
- assert result > 0
-
- def test_mixed_content(self):
- """Mixed content (text, numbers, special chars) should work."""
- result = count_tokens("Hello123!@#World")
- assert result > 0
-
- def test_newlines(self):
- """Text with newlines should be tokenized."""
- result = count_tokens("Hello\nWorld\nTest")
- assert result > 0
-
- def test_code_snippet(self):
- """Code snippets should be tokenized."""
- code = """
-def hello():
- print("Hello, World!")
-"""
- result = count_tokens(code)
- assert result > 5 # Code should have multiple tokens
-
- def test_json_content(self):
- """JSON content should be tokenized."""
- json_str = '{"key": "value", "number": 123}'
- result = count_tokens(json_str)
- assert result > 0
-
- def test_url(self):
- """URLs should be tokenized."""
- result = count_tokens("https://www.example.com/path?query=value")
- assert result > 0
-
- def test_consistency(self):
- """Same input should always produce same output."""
- text = "This is a test sentence."
- result1 = count_tokens(text)
- result2 = count_tokens(text)
- assert result1 == result2
-
- def test_very_long_text(self):
- """Very long text should be handled."""
- long_text = "word " * 1000
- result = count_tokens(long_text)
- assert result > 100 # Should have many tokens
-
- def test_token_count_approximation(self):
- """Token count should be roughly 1 token per 4 chars for English."""
- text = "This is a sample text for testing token count approximation."
- result = count_tokens(text)
- # GPT tokenizers typically produce ~1 token per 4 characters
- char_count = len(text)
- assert result > char_count / 10 # Very loose lower bound
- assert result < char_count # Token count should be less than char count
-
-
-class TestApproxCountTokens:
- """Tests for approx_count_tokens function (character-based heuristic)."""
-
- def test_empty_string(self):
- assert approx_count_tokens("") == 0
-
- def test_ceil_division_by_four(self):
- assert approx_count_tokens("a") == 1
- assert approx_count_tokens("abcd") == 1
- assert approx_count_tokens("abcde") == 2
-
- def test_returns_integer(self):
- assert isinstance(approx_count_tokens("test"), int)
-
- def test_no_tiktoken_encode(self, monkeypatch):
- """The heuristic must not invoke tiktoken encoding regardless of load state."""
-
- def _boom() -> None:
- raise AssertionError("approx_count_tokens must not load the encoding")
-
- monkeypatch.setattr("skyvern.utils.token_counter._get_encoding", _boom)
- assert approx_count_tokens("word " * 1000) == 1250
-
- def test_gate_threshold_behavior(self):
- """Large HTML should exceed the 100k-token gate via the cheap estimate."""
- assert approx_count_tokens("x" * 500_000) == 125_000
diff --git a/tests/unit_tests/test_update_status_guard.py b/tests/unit_tests/test_update_status_guard.py
deleted file mode 100644
index 8ba7b6905..000000000
--- a/tests/unit_tests/test_update_status_guard.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""Tests for the update_status finalization guard in default_persistent_sessions_manager."""
-
-from __future__ import annotations
-
-import sys
-from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-
-# Stub the AWS module to avoid import-time boto session creation.
-sys.modules.setdefault("skyvern.forge.sdk.api.aws", MagicMock())
-
-from skyvern.forge.sdk.schemas.persistent_browser_sessions import ( # noqa: E402
- PersistentBrowserSession,
- PersistentBrowserSessionStatus,
-)
-from skyvern.webeye.default_persistent_sessions_manager import update_status # noqa: E402
-
-SESSION_ID = "sess_1"
-ORG_ID = "org_1"
-NOW = datetime.now(timezone.utc)
-
-
-def _make_session(status: str) -> PersistentBrowserSession:
- return PersistentBrowserSession(
- persistent_browser_session_id=SESSION_ID,
- organization_id=ORG_ID,
- status=status,
- created_at=NOW,
- modified_at=NOW,
- )
-
-
- "desired_status",
- [
- pytest.param(PersistentBrowserSessionStatus.running, id="non-final-to-final"),
- pytest.param(PersistentBrowserSessionStatus.failed, id="final-to-final"),
- ],
-)
-async def test_rejects_update_when_already_final(desired_status: str):
- """A finalized session must not accept any status update."""
- db = AsyncMock()
- db.browser_sessions.get_persistent_browser_session.return_value = _make_session(
- PersistentBrowserSessionStatus.completed,
- )
-
- result = await update_status(db, SESSION_ID, ORG_ID, desired_status)
-
- assert result is None
- db.update_persistent_browser_session.assert_not_called()
diff --git a/tests/unit_tests/test_url_validators_extended.py b/tests/unit_tests/test_url_validators_extended.py
deleted file mode 100644
index d41a128fd..000000000
--- a/tests/unit_tests/test_url_validators_extended.py
+++ /dev/null
@@ -1,183 +0,0 @@
-"""Extended tests for URL validators module."""
-
-import re
-
-import pytest
-
-from skyvern.exceptions import InvalidUrl
-from skyvern.utils.url_validators import encode_url, prepend_scheme_and_validate_url
-
-
-class TestEncodeUrl:
- """Tests for encode_url function."""
-
- def test_encode_simple_path(self):
- """Simple path with spaces should be encoded."""
- url = "https://example.com/path with spaces"
- result = encode_url(url)
- assert result == "https://example.com/path%20with%20spaces"
-
- def test_encode_query_params(self):
- """Query parameters with spaces should be encoded."""
- url = "https://example.com/search?q=hello world"
- result = encode_url(url)
- assert result == "https://example.com/search?q=hello%20world"
-
- def test_preserve_slashes_in_path(self):
- """Slashes in path should be preserved."""
- url = "https://example.com/path/to/resource"
- result = encode_url(url)
- assert result == "https://example.com/path/to/resource"
-
- def test_preserve_existing_encoding(self):
- """Already encoded characters should be preserved."""
- url = "https://example.com/path%20already%20encoded"
- result = encode_url(url)
- assert result == "https://example.com/path%20already%20encoded"
-
- def test_encode_special_characters(self):
- """Special characters in path should be encoded."""
- url = "https://example.com/path<with>brackets"
- result = encode_url(url)
- # Angle brackets should be percent-encoded
- assert result == "https://example.com/path%3Cwith%3Ebrackets"
-
- def test_preserve_query_structure(self):
- """Query string structure (= and &) should be preserved."""
- url = "https://example.com/search?key1=value1&key2=value2"
- result = encode_url(url)
- assert "key1=value1" in result
- assert "key2=value2" in result
- assert "&" in result
-
- def test_empty_path(self):
- """URL with empty path should work."""
- url = "https://example.com"
- result = encode_url(url)
- assert result == "https://example.com"
-
- def test_encode_unicode_path(self):
- """Unicode characters in path should be encoded."""
- url = "https://example.com/路径"
- result = encode_url(url)
- # Unicode should be percent-encoded, original characters should not appear
- assert "路径" not in result
- # re.search rather than ``in``: CodeQL's py/incomplete-url-substring-sanitization reads a
- # hostname-literal ``in`` check as broken sanitization (OSS alert #89); this is an assertion.
- assert re.search(r"example\.com/", result)
- # "路径" in UTF-8 is encoded as %E8%B7%AF%E5%BE%84
- assert "%E8%B7%AF%E5%BE%84" in result
-
- def test_fragment_preserved(self):
- """URL fragments should be preserved."""
- url = "https://example.com/page#section"
- result = encode_url(url)
- # Fragment should be preserved in the output
- assert result == "https://example.com/page#section"
-
-
-class TestPrependSchemeAndValidateUrl:
- """Tests for prepend_scheme_and_validate_url function."""
-
- def test_empty_url_returns_empty(self):
- """Empty URL should return empty string."""
- assert prepend_scheme_and_validate_url("") == ""
-
- def test_https_url_unchanged(self):
- """URL with https scheme should remain unchanged."""
- url = "https://example.com"
- result = prepend_scheme_and_validate_url(url)
- assert result == url
-
- def test_http_url_unchanged(self):
- """URL with http scheme should remain unchanged."""
- url = "http://example.com"
- result = prepend_scheme_and_validate_url(url)
- assert result == url
-
- def test_no_scheme_gets_https(self):
- """URL without scheme should get https prepended."""
- url = "example.com"
- result = prepend_scheme_and_validate_url(url)
- assert result == "https://example.com"
-
- def test_invalid_scheme_raises_error(self):
- """URL with invalid scheme should raise InvalidUrl."""
- with pytest.raises(InvalidUrl):
- prepend_scheme_and_validate_url("ftp://example.com")
-
- def test_file_scheme_raises_error(self):
- """URL with file scheme should raise InvalidUrl."""
- with pytest.raises(InvalidUrl):
- prepend_scheme_and_validate_url("file:///etc/passwd")
-
- def test_javascript_scheme_raises_error(self):
- """URL with javascript scheme should raise InvalidUrl."""
- with pytest.raises(InvalidUrl):
- prepend_scheme_and_validate_url("javascript:alert(1)")
-
- def test_valid_url_with_path(self):
- """Valid URL with path should work."""
- url = "https://example.com/path/to/resource"
- result = prepend_scheme_and_validate_url(url)
- assert result == url
-
- def test_valid_url_with_query(self):
- """Valid URL with query parameters should work."""
- url = "https://example.com/search?q=test"
- result = prepend_scheme_and_validate_url(url)
- assert result == url
-
- def test_url_with_port(self):
- """URL with port number should work."""
- url = "https://example.com:8080/path"
- result = prepend_scheme_and_validate_url(url)
- assert result == url
-
- def test_subdomain_url(self):
- """URL with subdomain should work."""
- url = "https://api.example.com/v1"
- result = prepend_scheme_and_validate_url(url)
- assert result == url
-
- def test_invalid_url_raises_error(self):
- """Completely invalid URL should raise InvalidUrl."""
- with pytest.raises(InvalidUrl):
- prepend_scheme_and_validate_url("not a valid url at all!!!")
-
- @pytest.mark.parametrize("url", ["http://[", "http://[::1", "https://]"])
- def test_malformed_ipv6_raises_invalid_url_not_value_error(self, url):
- """Unterminated IPv6 literals make stdlib urlparse raise ValueError; it must surface as InvalidUrl."""
- with pytest.raises(InvalidUrl):
- prepend_scheme_and_validate_url(url)
-
-
-class TestEncodeUrlEdgeCases:
- """Edge case tests for encode_url."""
-
- def test_double_slashes_in_path(self):
- """Double slashes in path should be preserved."""
- url = "https://example.com//double//slashes"
- result = encode_url(url)
- assert "//double//slashes" in result
-
- def test_url_with_credentials(self):
- """URL with credentials should preserve the authority portion."""
- url = "https://user:[email protected]/path"
- result = encode_url(url)
- # Full authority portion including credentials should be preserved
- assert "user:[email protected]" in result
-
- def test_very_long_url(self):
- """Very long URL should be handled."""
- long_path = "/a" * 1000
- url = f"https://example.com{long_path}"
- result = encode_url(url)
- assert len(result) >= len(url)
-
- def test_url_with_multiple_query_params(self):
- """URL with multiple query parameters should work."""
- url = "https://example.com/search?a=1&b=2&c=3&d=4&e=5"
- result = encode_url(url)
- assert "a=1" in result
- assert "e=5" in result
diff --git a/tests/unit_tests/webeye/__init__.py b/tests/unit_tests/webeye/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/unit_tests/webeye/test_navigation_retry.py b/tests/unit_tests/webeye/test_navigation_retry.py
deleted file mode 100644
index d1a9d6a31..000000000
--- a/tests/unit_tests/webeye/test_navigation_retry.py
+++ /dev/null
@@ -1,746 +0,0 @@
-from __future__ import annotations
-
-import re
-import socket
-from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock
-
-import pytest
-import structlog.testing
-
-from skyvern.exceptions import (
- BlockedHost,
- BlockedNavigationDestination,
- FailedToNavigateToUrl,
- UnresolvableHost,
- UnresolvableNavigationHost,
-)
-from skyvern.webeye.navigation import (
- is_egress_attributable_navigation_failure,
- navigate_with_retry,
- redact_url_secrets,
- revalidate_redirect_chain,
- validate_navigation_destination,
-)
-from skyvern.webeye.real_browser_state import RealBrowserState
-
-
[email protected](autouse=True)
-def _resolve_navigation_hosts_to_public_address(monkeypatch: pytest.MonkeyPatch) -> None:
- def resolves_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:
- return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]
-
- monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_public)
-
-
-# Internal, loopback, link-local, metadata, and local-file targets that must fail closed.
-BLOCKED_DESTINATIONS = [
- pytest.param("file:///etc/passwd", id="local-file"),
- pytest.param("file://localhost/etc/shadow", id="local-file-host"),
- pytest.param("http://169.254.169.254/latest/meta-data/", id="cloud-metadata-ip"),
- pytest.param("http://169.254.1.1/", id="link-local"),
- pytest.param("http://192.168.0.10/admin", id="private-192"),
- pytest.param("http://10.0.0.5/", id="private-10"),
- pytest.param("http://127.0.0.1:9000/", id="loopback-ip"),
- pytest.param("http://localhost:8000/admin", id="localhost"),
- pytest.param("http://metadata.google.internal/computeMetadata/v1/", id="metadata-hostname"),
- pytest.param("http://kubernetes.default.svc/api", id="cluster-internal-svc"),
- # Numeric-IP and backslash-authority forms the browser normalizes to an internal host
- # even though stdlib urlparse / ipaddress do not (WHATWG canonicalization catches them).
- pytest.param("http://2130706433/", id="decimal-ip-loopback"),
- pytest.param("http://0177.0.0.1/", id="octal-ip-loopback"),
- pytest.param("http://0x7f.0.0.1/", id="hex-ip-loopback"),
- pytest.param("http://0xa9fea9fe/", id="hex-ip-metadata"),
- pytest.param("http://169.254.43518/", id="shortened-ip-metadata"),
- pytest.param(r"http://169.254.169.254\@example.com/", id="backslash-authority-metadata"),
- pytest.param(r"http:\\169.254.169.254/", id="all-backslash-authority"),
-]
-
-
-class _FakeRequest:
- """Duck-types the slice of playwright.async_api.Request that redirect revalidation reads."""
-
- def __init__(self, url: str, redirected_from: _FakeRequest | None = None) -> None:
- self.url = url
- self.redirected_from = redirected_from
-
-
-class _FakeResponse:
- def __init__(self, request: _FakeRequest) -> None:
- self.request = request
-
-
-def _redirect_response(*urls: str) -> _FakeResponse:
- """Build a page.goto-style response whose redirect chain visited ``urls`` in order."""
- request: _FakeRequest | None = None
- for url in urls:
- request = _FakeRequest(url, redirected_from=request)
- assert request is not None
- return _FakeResponse(request)
-
-
- "error_message",
- [
- pytest.param("net::ERR_NAME_NOT_RESOLVED", id="dns-not-resolved"),
- pytest.param("net::ERR_NAME_RESOLUTION_FAILED", id="dns-resolution-failed"),
- pytest.param("net::ERR_INVALID_URL", id="invalid-url"),
- pytest.param("net::ERR_CERT_AUTHORITY_INVALID", id="cert-authority-invalid"),
- pytest.param("net::ERR_CERT_DATE_INVALID", id="cert-date-invalid"),
- pytest.param("net::ERR_SSL_PROTOCOL_ERROR", id="ssl-protocol-error"),
- pytest.param("net::ERR_SOCKS_CONNECTION_FAILED", id="socks-connection-failed"),
- pytest.param("net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE", id="socks-host-unreachable"),
- ],
-)
-async def test_skip_inner_retry_error_fails_immediately(error_message: str) -> None:
- page = AsyncMock()
- page.goto = AsyncMock(side_effect=Exception(error_message))
- settle = AsyncMock()
- sleep = AsyncMock()
-
- with pytest.raises(FailedToNavigateToUrl):
- await navigate_with_retry(
- navigate=lambda strategy: page.goto("http://example.invalid", timeout=30000, wait_until=strategy),
- url="http://example.invalid",
- retry_times=5,
- settle=settle,
- sleep=sleep,
- )
-
- assert page.goto.call_count == 1
- settle.assert_not_awaited()
- sleep.assert_not_awaited()
-
-
- "error_message, retry_times",
- [
- pytest.param("net::ERR_TIMED_OUT", 3, id="timeout"),
- pytest.param("net::ERR_CONNECTION_RESET", 2, id="connection-reset"),
- ],
-)
-async def test_retriable_error_exhausts_all_attempts(
- error_message: str,
- retry_times: int,
-) -> None:
- page = AsyncMock()
- page.goto = AsyncMock(side_effect=Exception(error_message))
- settle = AsyncMock()
- sleep = AsyncMock()
-
- with pytest.raises(FailedToNavigateToUrl):
- await navigate_with_retry(
- navigate=lambda strategy: page.goto("http://example.com", timeout=30000, wait_until=strategy),
- url="http://example.com",
- retry_times=retry_times,
- settle=settle,
- sleep=sleep,
- )
-
- assert page.goto.call_count == retry_times
- assert sleep.await_count == retry_times - 1
- settle.assert_not_awaited()
-
-
-async def test_transient_error_recovers_on_retry() -> None:
- page = AsyncMock()
- page.goto = AsyncMock(side_effect=[Exception("net::ERR_CONNECTION_RESET"), None])
- settle = AsyncMock()
- sleep = AsyncMock()
-
- await navigate_with_retry(
- navigate=lambda strategy: page.goto("http://example.com", timeout=30000, wait_until=strategy),
- url="http://example.com",
- retry_times=3,
- settle=settle,
- sleep=sleep,
- )
-
- assert page.goto.call_count == 2
- assert sleep.await_count == 1
- settle.assert_awaited_once()
-
-
-async def test_get_or_create_page_does_not_retry_permanent_failed_navigation() -> None:
- browser_state = RealBrowserState(pw=AsyncMock())
- browser_state.get_working_page = AsyncMock(return_value=None)
- browser_state.check_and_fix_state = AsyncMock(
- side_effect=FailedToNavigateToUrl(
- url="http://example.invalid",
- error_message="net::ERR_INVALID_URL",
- )
- )
- browser_state.close_current_open_page = AsyncMock(return_value=True)
-
- with pytest.raises(FailedToNavigateToUrl):
- await browser_state.get_or_create_page(url="http://example.invalid")
-
- assert browser_state.check_and_fix_state.await_count == 1
- browser_state.close_current_open_page.assert_not_awaited()
-
-
-async def test_get_or_create_page_retries_dns_error_with_context_recreation() -> None:
- page = AsyncMock()
- browser_state = RealBrowserState(pw=AsyncMock())
- browser_state.get_working_page = AsyncMock(side_effect=[None, page])
- browser_state.check_and_fix_state = AsyncMock(
- side_effect=[
- FailedToNavigateToUrl(
- url="http://example.com",
- error_message="net::ERR_NAME_NOT_RESOLVED",
- ),
- None,
- ]
- )
- browser_state.close_current_open_page = AsyncMock(return_value=True)
- browser_state.validate_browser_context = AsyncMock(return_value=True)
- browser_state._RealBrowserState__assert_page = AsyncMock(return_value=page)
-
- result = await browser_state.get_or_create_page(url="http://example.com")
-
- assert result is page
- assert browser_state.check_and_fix_state.await_count == 2
- browser_state.close_current_open_page.assert_awaited_once()
- browser_state.validate_browser_context.assert_awaited_once_with(page)
-
-
-async def test_get_or_create_page_retries_retriable_failed_navigation() -> None:
- page = AsyncMock()
- browser_state = RealBrowserState(pw=AsyncMock())
- browser_state.get_working_page = AsyncMock(side_effect=[None, page])
- browser_state.check_and_fix_state = AsyncMock(
- side_effect=[
- FailedToNavigateToUrl(
- url="http://example.com",
- error_message="net::ERR_CONNECTION_RESET",
- ),
- None,
- ]
- )
- browser_state.close_current_open_page = AsyncMock(return_value=True)
- browser_state.validate_browser_context = AsyncMock(return_value=True)
- browser_state._RealBrowserState__assert_page = AsyncMock(return_value=page)
-
- result = await browser_state.get_or_create_page(url="http://example.com")
-
- assert result is page
- assert browser_state.check_and_fix_state.await_count == 2
- browser_state.close_current_open_page.assert_awaited_once()
- browser_state.validate_browser_context.assert_awaited_once_with(page)
-
-
-_DEAD_URL = "https://gone.example.com/search"
-
-
-def _no_such_host(*args: object, **kwargs: object) -> list[object]:
- raise socket.gaierror(socket.EAI_NONAME, "nodename nor servname provided, or not known")
-
-
-def _resolver_cannot_answer(*args: object, **kwargs: object) -> list[object]:
- raise socket.gaierror(socket.EAI_AGAIN, "Temporary failure in name resolution")
-
-
-async def _navigate_failing_with(error_message: str) -> FailedToNavigateToUrl:
- page = AsyncMock()
- page.goto = AsyncMock(side_effect=Exception(error_message))
-
- with pytest.raises(FailedToNavigateToUrl) as raised:
- await navigate_with_retry(
- navigate=lambda strategy: page.goto(_DEAD_URL, timeout=30000, wait_until=strategy),
- url=_DEAD_URL,
- retry_times=5,
- settle=AsyncMock(),
- sleep=AsyncMock(),
- )
-
- assert page.goto.call_count == 1
- return raised.value
-
-
- "error_message",
- [
- pytest.param("net::ERR_TUNNEL_CONNECTION_FAILED", id="tunnel"),
- pytest.param("net::ERR_SOCKS_CONNECTION_FAILED", id="socks"),
- ],
-)
-async def test_a_proxy_error_for_a_host_with_no_address_record_is_not_blamed_on_our_egress(
- monkeypatch: pytest.MonkeyPatch, error_message: str
-) -> None:
- # A proxied browser hands the hostname to the proxy, so a domain whose record is gone comes
- # back as the proxy failing to open a tunnel rather than as ERR_NAME_NOT_RESOLVED.
- monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _no_such_host)
-
- error = await _navigate_failing_with(error_message)
-
- assert isinstance(error, UnresolvableNavigationHost)
- assert error.host == "gone.example.com"
- assert is_egress_attributable_navigation_failure(error) is False
- # The browser's code is retained so downstream consumers still read the failure as terminal.
- assert error_message in error.error_message
-
-
-async def test_a_proxy_error_for_a_resolvable_host_stays_attributed_to_our_egress() -> None:
- # The autouse fixture resolves every host, so this is a genuine proxy fault and must keep the
- # recovery path that retries it on a different proxy node.
- error = await _navigate_failing_with("net::ERR_TUNNEL_CONNECTION_FAILED")
-
- assert not isinstance(error, UnresolvableNavigationHost)
- assert is_egress_attributable_navigation_failure(error) is True
-
-
-async def test_a_resolver_that_cannot_answer_does_not_reattribute_a_proxy_error(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # EAI_AGAIN means the resolver never answered. Reading it as a dead host would reclassify every
- # egress failure fleet-wide the moment worker DNS degrades.
- monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolver_cannot_answer)
-
- error = await _navigate_failing_with("net::ERR_TUNNEL_CONNECTION_FAILED")
-
- assert not isinstance(error, UnresolvableNavigationHost)
- assert is_egress_attributable_navigation_failure(error) is True
-
-
-async def test_get_or_create_page_does_not_redraw_a_proxy_node_for_an_unresolvable_host() -> None:
- browser_state = RealBrowserState(pw=AsyncMock())
- browser_state.get_working_page = AsyncMock(return_value=None)
- browser_state.check_and_fix_state = AsyncMock(
- side_effect=UnresolvableNavigationHost(
- url=_DEAD_URL,
- host="gone.example.com",
- error_message="net::ERR_TUNNEL_CONNECTION_FAILED",
- )
- )
- browser_state.close_current_open_page = AsyncMock(return_value=True)
-
- with pytest.raises(UnresolvableNavigationHost):
- await browser_state.get_or_create_page(url=_DEAD_URL)
-
- assert browser_state.check_and_fix_state.await_count == 1
- browser_state.close_current_open_page.assert_not_awaited()
-
-
[email protected]("url", BLOCKED_DESTINATIONS)
-def test_validate_navigation_destination_rejects_internal_and_local_targets(url: str) -> None:
- with pytest.raises(BlockedNavigationDestination):
- validate_navigation_destination(url)
-
-
- "url",
- [
- "https://example.com/path",
- "http://example.com/",
- "https://sub.example.co.uk/a?b=c",
- "example.com", # scheme-less public hosts are still allowed (https is prepended)
- ],
-)
-def test_validate_navigation_destination_allows_public_targets(url: str) -> None:
- validate_navigation_destination(url)
-
-
-def test_validate_navigation_destination_allows_a_host_the_worker_cannot_resolve(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:
- raise OSError("dns unavailable")
-
- monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)
-
- validate_navigation_destination("https://public.example.test/path")
-
-
[email protected]("url", BLOCKED_DESTINATIONS)
-def test_validate_navigation_destination_still_refuses_internal_targets_when_dns_fails(
- monkeypatch: pytest.MonkeyPatch, url: str
-) -> None:
- def fails_dns(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:
- raise OSError("dns unavailable")
-
- monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", fails_dns)
-
- with pytest.raises(BlockedNavigationDestination):
- validate_navigation_destination(url)
-
-
[email protected]("url", BLOCKED_DESTINATIONS)
-async def test_navigate_with_retry_blocks_internal_and_local_before_dispatch(url: str) -> None:
- navigate = AsyncMock()
- settle = AsyncMock()
- sleep = AsyncMock()
-
- with pytest.raises(BlockedNavigationDestination):
- await navigate_with_retry(navigate=navigate, url=url, retry_times=3, settle=settle, sleep=sleep)
-
- navigate.assert_not_awaited() # rejected before any request is dispatched
- settle.assert_not_awaited()
- sleep.assert_not_awaited()
-
-
-# Malformed authorities (unterminated IPv6 literals) that make stdlib urlparse raise a raw
-# ValueError; the guard must convert that to BlockedNavigationDestination before dispatch.
-MALFORMED_DESTINATIONS = [
- pytest.param("http://[", id="unterminated-ipv6-bracket"),
- pytest.param("http://[::1", id="unclosed-ipv6-literal"),
- pytest.param("https://]", id="stray-ipv6-close-bracket"),
-]
-
-
[email protected]("url", MALFORMED_DESTINATIONS)
-def test_validate_navigation_destination_rejects_malformed_urls(url: str) -> None:
- with pytest.raises(BlockedNavigationDestination):
- validate_navigation_destination(url)
-
-
[email protected]("url", MALFORMED_DESTINATIONS)
-async def test_navigate_with_retry_blocks_malformed_url_before_dispatch(url: str) -> None:
- navigate = AsyncMock()
- settle = AsyncMock()
- sleep = AsyncMock()
-
- with pytest.raises(BlockedNavigationDestination):
- await navigate_with_retry(navigate=navigate, url=url, retry_times=3, settle=settle, sleep=sleep)
-
- navigate.assert_not_awaited() # a parser error must not leak past the guard as a raw ValueError
- settle.assert_not_awaited()
- sleep.assert_not_awaited()
-
-
-async def test_navigate_with_retry_blocked_destination_is_a_navigation_failure() -> None:
- # Subclass of FailedToNavigateToUrl so existing navigation error handling catches it.
- navigate = AsyncMock()
- with pytest.raises(FailedToNavigateToUrl):
- await navigate_with_retry(
- navigate=navigate, url="http://169.254.169.254/", retry_times=3, settle=AsyncMock(), sleep=AsyncMock()
- )
-
-
-async def test_navigate_with_retry_revalidates_redirect_hops_and_fails_closed() -> None:
- navigate = AsyncMock(
- return_value=_redirect_response("https://example.com/start", "http://169.254.169.254/latest/meta-data/")
- )
- settle = AsyncMock()
- sleep = AsyncMock()
-
- with pytest.raises(BlockedNavigationDestination):
- await navigate_with_retry(
- navigate=navigate, url="https://example.com/start", retry_times=3, settle=settle, sleep=sleep
- )
-
- assert navigate.await_count == 1 # a blocked redirect is not retried
- settle.assert_not_awaited() # never settle a page that landed on an internal host
- sleep.assert_not_awaited()
-
-
-async def test_navigate_with_retry_allows_public_redirect_chain() -> None:
- navigate = AsyncMock(return_value=_redirect_response("http://example.com/start", "https://example.com/final"))
- settle = AsyncMock()
-
- await navigate_with_retry(
- navigate=navigate, url="http://example.com/start", retry_times=3, settle=settle, sleep=AsyncMock()
- )
-
- navigate.assert_awaited_once()
- settle.assert_awaited_once()
-
-
-async def test_navigate_with_retry_allows_public_navigation_without_response() -> None:
- navigate = AsyncMock(return_value=None)
- settle = AsyncMock()
-
- status = await navigate_with_retry(
- navigate=navigate, url="https://example.com/", retry_times=3, settle=settle, sleep=AsyncMock()
- )
-
- navigate.assert_awaited_once()
- settle.assert_awaited_once()
- assert status is None # no response object -> no status to carry
-
-
[email protected]("http_status", [200, 404, 410, 500])
-async def test_navigate_with_retry_returns_final_response_status(http_status: int) -> None:
- # The status is what lets the Task V3 loop classify a dead/removed starting URL, so navigate_with_retry
- # must surface the FINAL response's HTTP status (not swallow it as it did before).
- response = _redirect_response("https://example.com/")
- response.status = http_status # type: ignore[attr-defined]
- navigate = AsyncMock(return_value=response)
-
- result = await navigate_with_retry(
- navigate=navigate, url="https://example.com/", retry_times=3, settle=AsyncMock(), sleep=AsyncMock()
- )
-
- assert result == http_status
-
-
-# Empty and about:blank targets are non-egressing continuation/reconnect URLs that reach
-# navigate_with_retry (e.g. task.url="" browser_session continuation, `url or "about:blank"`
-# on reconnect); the fail-closed guard must let them through rather than reject them.
- "url",
- [pytest.param("", id="empty-string"), pytest.param("about:blank", id="about-blank")],
-)
-def test_validate_navigation_destination_allows_non_navigational_targets(url: str) -> None:
- validate_navigation_destination(url)
-
-
- "url",
- [pytest.param("", id="empty-string"), pytest.param("about:blank", id="about-blank")],
-)
-async def test_navigate_with_retry_allows_non_navigational_targets(url: str) -> None:
- navigate = AsyncMock(return_value=None)
- settle = AsyncMock()
-
- await navigate_with_retry(navigate=navigate, url=url, retry_times=3, settle=settle, sleep=AsyncMock())
-
- navigate.assert_awaited_once()
- settle.assert_awaited_once()
-
-
-async def test_navigate_with_retry_revalidates_every_redirect_hop() -> None:
- # An internal earliest hop followed by a long public tail: the whole chain must be
- # validated, not just the hops nearest the final URL.
- internal_first = "http://169.254.169.254/"
- public_tail = [f"https://hop{index}.example.com/" for index in range(14)]
- navigate = AsyncMock(return_value=_redirect_response(internal_first, *public_tail))
- settle = AsyncMock()
-
- with pytest.raises(BlockedNavigationDestination):
- await navigate_with_retry(
- navigate=navigate, url="https://start.example.com/", retry_times=3, settle=settle, sleep=AsyncMock()
- )
-
- settle.assert_not_awaited()
-
-
-async def test_revalidate_redirect_chain_checks_every_hop_and_the_final_destination() -> None:
- response = _redirect_response(
- "https://entry.example.test/a",
- "https://mid.example.test/b",
- "https://final.example.test/c",
- )
-
- seen: list[str] = []
- reset_page = AsyncMock()
- await revalidate_redirect_chain(response, seen.append, reset_page)
-
- assert sorted(seen) == [
- "https://entry.example.test/a",
- "https://final.example.test/c",
- "https://mid.example.test/b",
- ]
- reset_page.assert_not_awaited()
-
-
-async def test_revalidate_redirect_chain_propagates_the_validators_exception() -> None:
- response = _redirect_response(
- "https://entry.example.test/a",
- "http://169.254.169.254/latest/meta-data/",
- )
-
- refusal = BlockedHost("169.254.169.254")
- reset_page = AsyncMock()
-
- def refuse_metadata(url: str) -> None:
- if "169.254.169.254" in url:
- raise refusal
-
- with pytest.raises(BlockedHost) as exc_info:
- await revalidate_redirect_chain(response, refuse_metadata, reset_page)
-
- assert exc_info.value is refusal
- reset_page.assert_awaited_once_with("about:blank")
-
-
[email protected]("refusal", [BlockedHost("blocked.test"), UnresolvableHost("unresolvable.test")])
-async def test_revalidate_redirect_chain_preserves_refusal_when_page_reset_fails(
- monkeypatch: pytest.MonkeyPatch,
- refusal: BlockedHost,
-) -> None:
- response = _redirect_response(
- "https://entry.example.test/a",
- "http://169.254.169.254/latest/meta-data/",
- )
- reset_page = AsyncMock(side_effect=RuntimeError("reset failed"))
- log_exception = MagicMock()
- monkeypatch.setattr("skyvern.webeye.navigation.LOG.exception", log_exception)
-
- def refuse_metadata(url: str) -> None:
- if "169.254.169.254" in url:
- raise refusal
-
- with pytest.raises(type(refusal)) as exc_info:
- await revalidate_redirect_chain(response, refuse_metadata, reset_page)
-
- assert exc_info.value is refusal
- reset_page.assert_awaited_once_with("about:blank")
- log_exception.assert_called_once_with("Failed to reset page after redirect refusal")
-
-
-async def test_revalidate_redirect_chain_tolerates_a_response_without_a_request() -> None:
- calls: list[str] = []
-
- await revalidate_redirect_chain(None, calls.append)
- await revalidate_redirect_chain(SimpleNamespace(request=None), calls.append)
-
- assert calls == []
-
-
-def test_redact_url_secrets_keeps_only_scheme_and_host() -> None:
- assert redact_url_secrets("https://portal.example.com/verify/abc?token=xyz#frag") == (
- "https://portal.example.com/<redacted>"
- )
- assert redact_url_secrets("https://portal.example.com:8443/verify?token=xyz") == (
- "https://portal.example.com:8443/<redacted>"
- )
- assert redact_url_secrets("not a url") == "<redacted>"
-
-
-def test_redact_url_secrets_drops_basic_auth_credentials() -> None:
- """netloc carries user:password@; a redactor must not republish it."""
- redacted = redact_url_secrets("https://tok:[email protected]/verify?token=xyz")
-
- assert "s3cret" not in redacted
- assert "tok" not in redacted
- assert redacted == "https://portal.example.com/<redacted>"
-
-
-async def test_a_refused_secret_destination_does_not_report_the_real_url() -> None:
- """A self-hosted portal's link can legitimately resolve to a private host."""
- secret = "http://127.0.0.1/verify?token=super-secret-token-value"
-
- async def navigate(strategy: str) -> object:
- raise AssertionError("must not navigate to a blocked destination")
-
- async def settle() -> None:
- return None
-
- with structlog.testing.capture_logs() as logs:
- with pytest.raises(BlockedNavigationDestination) as excinfo:
- await navigate_with_retry(
- navigate=navigate,
- url=secret,
- retry_times=2,
- settle=settle,
- log_url=redact_url_secrets(secret),
- )
-
- assert "super-secret-token-value" not in str(excinfo.value)
- assert "super-secret-token-value" not in repr(logs)
- # The chained cause would carry the original message into any rendered traceback.
- assert excinfo.value.__cause__ is None
-
-
-async def test_log_url_keeps_the_real_url_out_of_logs_and_the_failure_reason() -> None:
- """A sign-in link is a bearer credential: navigate to it, but never log or report it."""
- secret = "https://portal.example.com/verify?token=super-secret-token-value"
-
- async def navigate(strategy: str) -> object:
- # Playwright names the destination in its own message, so the secret arrives via the
- # error text as well as the url field.
- raise RuntimeError(f"Page.goto: net::ERR_CONNECTION_REFUSED at {secret}")
-
- async def settle() -> None:
- return None
-
- async def no_sleep(_seconds: float) -> None:
- return None
-
- with structlog.testing.capture_logs() as logs:
- with pytest.raises(FailedToNavigateToUrl) as excinfo:
- await navigate_with_retry(
- navigate=navigate,
- url=secret,
- retry_times=2,
- settle=settle,
- sleep=no_sleep,
- log_url=redact_url_secrets(secret),
- )
-
- assert "super-secret-token-value" not in str(excinfo.value)
- assert "super-secret-token-value" not in repr(logs)
- # The host still reaches the operator, so a failure stays diagnosable. re.search rather
- # than ``in``: CodeQL's py/incomplete-url-substring-sanitization reads a hostname-literal
- # ``in`` check as broken sanitization; this is an assertion, not a sanitizer.
- assert any(re.search(r"portal\.example\.com", repr(entry)) for entry in logs)
-
-
-async def test_a_refused_redirect_hop_is_redacted_for_a_secret_caller() -> None:
- """The hop that gets refused is a different URL than the one requested; redact that one."""
- secret = "https://portal.example.com/verify?token=super-secret-token-value"
- # A literal loopback address is refused before DNS, unlike the hostnames the suite's
- # autouse fixture resolves to a public address.
- hop = "http://127.0.0.1/r?dest=internal&session=hop-secret-value"
-
- async def navigate(strategy: str) -> object:
- return SimpleNamespace(request=SimpleNamespace(url=hop, redirected_from=None))
-
- async def settle() -> None:
- return None
-
- with structlog.testing.capture_logs() as logs:
- with pytest.raises(BlockedNavigationDestination) as excinfo:
- await navigate_with_retry(
- navigate=navigate,
- url=secret,
- retry_times=2,
- settle=settle,
- log_url=redact_url_secrets(secret),
- )
-
- assert "hop-secret-value" not in str(excinfo.value)
- assert "hop-secret-value" not in repr(logs)
- assert "super-secret-token-value" not in str(excinfo.value)
- # The refused hop's host still identifies what was blocked.
- assert "127.0.0.1" in str(excinfo.value)
- assert excinfo.value.__cause__ is None
-
-
-async def test_navigation_still_targets_the_real_url_when_a_display_url_is_given() -> None:
- secret = "https://portal.example.com/verify?token=super-secret-token-value"
- navigated: list[str] = []
-
- async def navigate(strategy: str) -> object:
- navigated.append(secret)
- return None
-
- async def settle() -> None:
- return None
-
- await navigate_with_retry(
- navigate=navigate,
- url=secret,
- retry_times=1,
- settle=settle,
- log_url=redact_url_secrets(secret),
- )
-
- assert navigated == [secret]