Testing
This page is for the practitioner who is writing tests for code that uses the SDK and needs reliable, fast, network-free fixtures. The SDK is designed to be testable without a Viya tenant; the patterns below are the ones the SDK's own test suite uses.
Three layers of test fidelity
| Layer | What it gives you | When to use |
|---|---|---|
| Stubbed services | Each service replaced with MagicMock | Pure logic tests; verifying what your code calls |
| Mock transport | Real SVIClient + httpx2.MockTransport | End-to-end tests of typed inputs/outputs through the SDK |
| Live tenant | Real client against a test deployment | Live integration; rarely in unit tests |
Start with stubbed services for most tests; promote to mock transport when you need to verify serialization, retry behavior, or typed exception handling.
Stubbed-services pattern
object.__new__(SVIClient) builds an instance without running __init__. That
matters because __init__ has two side effects that make tests slow and brittle: it
builds the HTTP clients and their shared connection pool, and it resolves auth.
from typing import Any
from unittest.mock import MagicMock
import pytest
import sasvi
from sasvi.config import SVIConfig
@pytest.fixture
def stub_client():
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(stub_client):
stub_client.alerts.get.return_value = type(
"Alert",
(),
{"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 == 42
MagicMock() is a duck-typed stand-in: stub.alerts.get(...) returns whatever you
set as return_value. Use it to assert that the right call was made without
needing real SDK behavior.
Mock-transport pattern
For tests that need real SDK behavior, such as typed responses, retry and error
handling, swap the underlying httpx2 transport instead of the services. Answer each
exact route with the payload its service sends, in camelCase: alerts.get reads the
alert, then the alert's document from Data Hub.
import httpx2
import pytest
import sasvi
ALERT = {"alertId": "abc", "currentScore": 42}
ALERT_DOCUMENT = {"objectTypeName": "alerts", "id": "abc", "fieldValues": {"alert_id": "abc"}}
@pytest.fixture
def mocked_client():
def handler(request: httpx2.Request) -> httpx2.Response:
path = request.url.path
if path == "/svi-alert/alerts/abc":
return httpx2.Response(200, json=ALERT)
if path == "/svi-datahub/documents/alerts/abc":
return httpx2.Response(200, json=ALERT_DOCUMENT)
if path in ("/svi-alert/alerts/missing", "/svi-datahub/documents/alerts/missing"):
return httpx2.Response(404, json={"message": "not found"})
return httpx2.Response(500, json={"message": f"unmocked {request.method} {path}"})
client = sasvi.SVIClient(
base_url="https://viya.example.test",
auth=sasvi.StaticTokenProvider("test-token"),
sync_httpx_args={"transport": httpx2.MockTransport(handler)},
async_httpx_args={"transport": httpx2.MockTransport(handler)},
max_retries=0,
)
yield client
client.close()
def test_found(mocked_client):
alert = mocked_client.alerts.get(alert_id="abc")
assert alert.alert_id == "abc"
assert alert.current_score == 42
def test_missing_returns_none(mocked_client):
alert = mocked_client.alerts.get(alert_id="missing")
assert alert is None
The MockTransport handler gets every HTTP request the SDK makes, so you can assert
request paths, inspect bodies, and return different responses per call. The SDK's own
retry, deserialization, and typed exception logic all runs.
max_retries=0 is important in tests. Without it, a test that returns a retryable
status (503) loops for 4 attempts before failing.
Async testing
The SDK's async siblings work through httpx2.MockTransport too. AnyIO's pytest
plugin is installed with httpx2, so @pytest.mark.anyio runs an async test with no
extra package. With ALERT and ALERT_DOCUMENT from above:
import httpx2
import pytest
import sasvi
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_async_flow():
routes = {
"/svi-alert/alerts/abc": ALERT,
"/svi-datahub/documents/alerts/abc": ALERT_DOCUMENT,
}
def handler(request: httpx2.Request) -> httpx2.Response:
if request.url.path in routes:
return httpx2.Response(200, json=routes[request.url.path])
return httpx2.Response(500, json={"message": f"unmocked {request.url.path}"})
async with sasvi.SVIClient(
base_url="https://viya.example.test",
auth=sasvi.StaticTokenProvider("test-token"),
async_httpx_args={"transport": httpx2.MockTransport(handler)},
sync_httpx_args={"transport": httpx2.MockTransport(handler)},
max_retries=0,
) as client:
alert = await client.alerts.get_async(alert_id="abc")
assert alert.alert_id == "abc"
assert alert.current_score == 42
With pytest-asyncio instead, mark the test @pytest.mark.asyncio, or set
asyncio_mode = "auto" under [tool.pytest.ini_options] to drop the marker.
Pass the mock to sync_httpx_args as well, so a sync call in the test cannot reach the
network. Insight-cell and workspace-node editing are sync-only.
Testing typed exceptions
import pytest
import sasvi
from sasvi import errors
def test_disposition_prompt(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"
assert exc_info.value.status_code is None # SDK populates from upstream
Catch by type, then assert on the structured attributes (missing, disposition_id,
status_code, error_code, details, remediation). See
Errors reference.
Testing retry behavior
Count attempts per route: after the alert read succeeds, alerts.get makes one more
request, for the alert's document. With ALERT and ALERT_DOCUMENT from above:
import httpx2
import sasvi
def test_retries_503_then_succeeds():
attempts = {"alert": 0, "document": 0}
def handler(request: httpx2.Request) -> httpx2.Response:
if request.url.path == "/svi-alert/alerts/abc":
attempts["alert"] += 1
if attempts["alert"] < 3:
return httpx2.Response(503, json={"message": "transient"})
return httpx2.Response(200, json=ALERT)
if request.url.path == "/svi-datahub/documents/alerts/abc":
attempts["document"] += 1
return httpx2.Response(200, json=ALERT_DOCUMENT)
return httpx2.Response(500, json={"message": f"unmocked {request.url.path}"})
with sasvi.SVIClient(
base_url="https://viya.example.test",
auth=sasvi.StaticTokenProvider("test-token"),
sync_httpx_args={"transport": httpx2.MockTransport(handler)},
max_retries=3,
retry_backoff_seconds=0,
) as client:
alert = client.alerts.get(alert_id="abc")
assert alert.current_score == 42
assert attempts == {"alert": 3, "document": 1} # two 503s, then the 200
Set retry_backoff_seconds=0 in tests so the retry loop doesn't sleep.
Testing the deadline cap
import httpx2
import pytest
import sasvi
from sasvi import errors
def test_deadline_is_enforced():
def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(503)
client = sasvi.SVIClient(
auth=sasvi.StaticTokenProvider("test-token"),
config=sasvi.SVIConfig(
base_url="https://viya.example.test",
max_retries=10,
retry_backoff_seconds=1.0,
request_deadline_seconds=2.0,
sync_httpx_args={"transport": httpx2.MockTransport(handler)},
),
)
# DeadlineExceededError is a TransientError, so either catch works.
with pytest.raises(errors.DeadlineExceededError):
client.alerts.get(alert_id="abc")
VCR-style cassettes
For high-fidelity reproductions of real Viya responses, VCR.py records real HTTP interactions and replays them in tests. A cassette stores every request and response in plain text, so by default it holds your bearer token, any SAS Logon password or client secret, the tokens SAS Logon returned, and whatever tenant data the responses carried. Scrub all of that before anything is written:
import json
import os
import sasvi
import vcr
SECRET_FORM_FIELDS = ["password", "client_secret", "refresh_token", "code", "assertion"]
def scrub_token_response(response):
"""Replace a SAS Logon token response with a placeholder body."""
body = response["body"]["string"]
if b"access_token" in body:
response["body"]["string"] = json.dumps({
"access_token": "REDACTED",
"token_type": "bearer",
"expires_in": 3600,
}).encode()
return response
my_vcr = vcr.VCR(
serializer="yaml",
cassette_library_dir="tests/cassettes",
match_on=["method", "scheme", "host", "path", "query"],
filter_headers=["authorization", "cookie", "set-cookie", "x-csrf-token"],
filter_query_parameters=["access_token", "code"],
filter_post_data_parameters=SECRET_FORM_FIELDS,
before_record_response=scrub_token_response,
decode_compressed_response=True,
)
@my_vcr.use_cassette("alert_get_abc.yaml")
def test_real_response():
# A static token keeps SAS Logon out of the recording entirely.
client = sasvi.SVIClient(
base_url="https://viya.example.com",
auth=sasvi.StaticTokenProvider(os.environ["SASVI_ACCESS_TOKEN"]),
)
alert = client.alerts.get(alert_id="abc")
assert alert is not None
Record against a test tenant that holds no real investigation data, then read each cassette before you commit it: the filters remove credentials, not the tenant host name or the field values in the responses. Never commit a cassette recorded against a production tenant.
Add vcrpy to your test dependencies (not the SDK's); cassettes pin you to the
recorded responses, so re-record when the SDK or VI evolves.
Fixtures the SDK uses internally
The SDK's own test suite uses two patterns worth borrowing. Both live in
tests/test_client_helpers.py in the SDK repository.
Full real client with mock transport
@pytest.fixture
def real_like_client():
def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(200, json={})
client = sasvi.SVIClient(
base_url="https://viya.example.test",
auth=sasvi.StaticTokenProvider("test"),
sync_httpx_args={"transport": httpx2.MockTransport(handler)},
async_httpx_args={"transport": httpx2.MockTransport(handler)},
max_retries=0,
)
yield client
client.close()
Use this when you want every SDK layer to participate in the test.
object.__new__(SVIClient): stubbed services for logic-only tests
@pytest.fixture
def stub_client():
client = object.__new__(sasvi.SVIClient)
client.runtime_config = SVIConfig(base_url="https://viya.example.test")
client.alerts = MagicMock()
client.documents = MagicMock()
client.admin = MagicMock()
# ... etc
return client
Use this when the test is about your code, not the SDK's behavior.
Common test mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Forgot to disable retries | Test hangs on a 503 response | max_retries=0 |
Forgot to set retry_backoff_seconds=0 | Test is slow | Override in the test client |
| Used a real bearer token | Test calls a real tenant | Use StaticTokenProvider("test") |
| Mocked only sync transport for an async test | httpx2.AsyncClient makes real calls | Pass the same MockTransport to async_httpx_args |
SVIClient(...) constructor too slow | Builds HTTP clients and resolves auth | Use object.__new__(SVIClient) for stubbed tests |
Asserting on __repr__ strings | Repr changes break tests | Assert on attributes, not repr() |
Go further
- Mock SDK in pytest recipe. A copy-paste fixture.
- Errors reference. Typed exception attributes to assert on.
- Async deep dive. Patterns for testing concurrent code.