Mock the SDK in pytest
Stub SVIClient with object.__new__ and monkeypatch so your unit tests run without
a Viya tenant. This is the pattern the SDK itself uses in
tests/test_client_helpers.py.
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock
import pytest
import sasvi
from sasvi.config import SVIConfig
@pytest.fixture
def stub_client(monkeypatch):
"""Return an SVIClient with every service replaced by a MagicMock."""
client = object.__new__(sasvi.SVIClient)
client.runtime_config = SVIConfig(base_url="https://viya.example.test")
client.auth = MagicMock()
client.api = MagicMock()
client.admin = MagicMock()
client.alerts = MagicMock()
client.documents = MagicMock()
client.search = MagicMock()
client.workflows = MagicMock()
client.custom = MagicMock()
client._echo_connection = False
client._connection_verified = False
return client
def test_my_function_passes_alert_id(stub_client):
stub_client.alerts.get.return_value = SimpleNamespace(
alert_id="abc",
current_score=42,
)
result = my_function(stub_client, alert_id="abc")
stub_client.alerts.get.assert_called_once_with(alert_id="abc")
assert result.current_score == 42
object.__new__(SVIClient) builds an instance without running __init__. That
matters because __init__ imports every generated client module and resolves auth.
Those side effects make most tests slow and brittle.
Mock at the HTTP transport layer
For higher-fidelity tests, swap the underlying transport rather than the service.
alerts.get makes two requests: it reads the alert from the alerts service, then the
alert's document from Data Hub. Each route answers with the payload its service sends,
in the service's own camelCase field names, and any other request fails the test so a
wrong route cannot pass quietly.
import httpx2
import pytest
import sasvi
ROUTES = {
# The alert, as the alerts service returns it.
"/svi-alert/alerts/abc": {"alertId": "abc", "currentScore": 42},
# The alert's document, which alerts.get reads next from Data Hub.
"/svi-datahub/documents/alerts/abc": {
"objectTypeName": "alerts",
"id": "abc",
"fieldValues": {"alert_id": "abc"},
},
}
def handler(request: httpx2.Request) -> httpx2.Response:
if request.method == "GET" and request.url.path in ROUTES:
return httpx2.Response(200, json=ROUTES[request.url.path])
return httpx2.Response(500, json={"message": f"unmocked {request.method} {request.url.path}"})
def make_client() -> sasvi.SVIClient:
transport = httpx2.MockTransport(handler)
return sasvi.SVIClient(
base_url="https://viya.example.test",
auth=sasvi.StaticTokenProvider("test-token"),
sync_httpx_args={"transport": transport},
async_httpx_args={"transport": transport},
max_retries=0,
)
@pytest.fixture
def real_client():
client = make_client()
yield client
client.close()
def test_real_path(real_client):
alert = real_client.alerts.get(alert_id="abc")
assert alert.alert_id == "abc"
assert alert.current_score == 42
Test typed exception handling
import pytest
import sasvi
from sasvi import errors
def test_disposition_prompt_propagates(stub_client):
stub_client.alerts.get.return_value.disposition.side_effect = (
errors.DispositionPromptRequiredError(
"missing note",
missing=("note", "reason_code"),
disposition_id="def",
)
)
with pytest.raises(errors.DispositionPromptRequiredError) as exc_info:
my_disposition_flow(stub_client, alert_id="abc")
assert exc_info.value.missing == ("note", "reason_code")
assert exc_info.value.disposition_id == "def"
Test async
httpx2.MockTransport serves async requests too. With make_client from above:
import pytest
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_async_flow():
client = make_client()
try:
alert = await client.alerts.get_async(alert_id="abc")
assert alert.alert_id == "abc"
assert alert.current_score == 42
finally:
await client.close_async() # closes the sync and the async transports
The anyio marker comes from AnyIO's pytest plugin, which is installed with httpx2, so
this needs no extra package. With pytest-asyncio, use @pytest.mark.asyncio instead
and drop the anyio_backend fixture.
Go further
- Testing guide. Fuller patterns, pytest-asyncio setup, VCR.
- Errors reference. The typed exception hierarchy.