Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/langsmith/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,8 @@ def pytest_configure(config):
raise ValueError(msg)
if ls_utils.test_tracking_is_disabled():
msg = (
"--langsmith-output not supported when env var"
"LANGSMITH_TEST_TRACKING='false'. Please remove the"
"--langsmith-output not supported when env var "
"LANGSMITH_TEST_TRACKING='false'. Please remove the "
"'--langsmith-output' option "
"or enable test tracking."
)
Expand Down
16 changes: 14 additions & 2 deletions src/langsmith/testing/_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1045,8 +1045,14 @@ def _test():
ignore_hosts = [test_case.test_suite.client.api_url]
allow_hosts = langtest_extra.get("cached_hosts") or None

# This only runs with test tracking on, so the test's own trace must be
# recorded even when LANGSMITH_TRACING is unset: otherwise no run tree is
# set, log_* raise, and the experiment gets no runs. An explicit
# tracing_context(enabled=...) around the test still takes precedence.
enabled = True if current_context["enabled"] is None else current_context["enabled"]

with (
rh.tracing_context(**{**current_context, "metadata": metadata}),
rh.tracing_context(**{**current_context, "metadata": metadata, "enabled": enabled}),
ls_utils.with_optional_cache(cache_path, ignore_hosts=ignore_hosts, allow_hosts=allow_hosts),
):
_test()
Expand Down Expand Up @@ -1124,8 +1130,14 @@ async def _test():
cached_hosts = langtest_extra.get("cached_hosts")
allow_hosts = cached_hosts if cached_hosts else None

# This only runs with test tracking on, so the test's own trace must be
# recorded even when LANGSMITH_TRACING is unset: otherwise no run tree is
# set, log_* raise, and the experiment gets no runs. An explicit
# tracing_context(enabled=...) around the test still takes precedence.
enabled = True if current_context["enabled"] is None else current_context["enabled"]

with (
rh.tracing_context(**{**current_context, "metadata": metadata}),
rh.tracing_context(**{**current_context, "metadata": metadata, "enabled": enabled}),
ls_utils.with_optional_cache(cache_path, ignore_hosts=ignore_hosts, allow_hosts=allow_hosts),
):
await _test()
Expand Down
17 changes: 17 additions & 0 deletions tests/unit_tests/test_pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,20 @@ def test_table_counts_collected_tests_without_results():
assert "test_example.py::test_missing" in output
assert "queued" in output
assert "50%" in output


def test_langsmith_output_with_tracking_disabled_error_is_readable(monkeypatch):
monkeypatch.setattr(pytest_plugin.ls_utils, "test_tracking_is_disabled", lambda: True)
monkeypatch.delenv("PYTEST_XDIST_TESTRUNUID", raising=False)
config = SimpleNamespace(
addinivalue_line=lambda *args: None,
getoption=lambda name: name == "--langsmith-output",
)

with pytest.raises(ValueError) as exc_info:
pytest_plugin.pytest_configure(config)

assert str(exc_info.value) == (
"--langsmith-output not supported when env var LANGSMITH_TEST_TRACKING='false'. "
"Please remove the '--langsmith-output' option or enable test tracking."
)
89 changes: 89 additions & 0 deletions tests/unit_tests/test_testing.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import asyncio
import datetime
import uuid
from unittest.mock import MagicMock

import pytest

from langsmith import run_helpers as rh
from langsmith import testing as t
from langsmith import utils as ls_utils
from langsmith.testing import _internal
from langsmith.testing._internal import (
_arun_test,
_get_example_id,
_LangSmithTestSuite,
_run_test,
_serde_example_values,
_TestCase,
)
Expand Down Expand Up @@ -100,3 +109,83 @@ def test_pytest_feedback_includes_experiment_id_and_run_start_time():
assert call.args[0] == run_id
assert call.kwargs["session_id"] == experiment_id
assert call.kwargs["start_time"] == start_time


def _make_tracked_test_case(monkeypatch):
test_suite = MagicMock()
test_suite.id = uuid.uuid4()
test_suite.name = "test-suite"
test_suite.client.api_url = "https://api.smith.langchain.com"
test_case = _TestCase(test_suite=test_suite, run_id=uuid.uuid4(), inputs={})
monkeypatch.setattr(_internal, "_create_test_case", lambda *args, **kwargs: test_case)
return test_case


@pytest.fixture
def tracing_env_unset(monkeypatch):
for var in ("LANGSMITH_TRACING", "LANGSMITH_TRACING_V2", "LANGCHAIN_TRACING", "LANGCHAIN_TRACING_V2"):
monkeypatch.delenv(var, raising=False)
ls_utils.get_env_var.cache_clear()
yield
ls_utils.get_env_var.cache_clear()


def test_log_functions_work_with_tracking_on_and_tracing_env_unset(monkeypatch, tracing_env_unset):
"""Test tracking alone must be enough for log_* (issue #107)."""
test_case = _make_tracked_test_case(monkeypatch)
client = MagicMock()
seen = {}

def tracked_test():
t.log_inputs({"q": "2+2"})
t.log_outputs({"a": 4})
seen["run_tree"] = rh.get_current_run_tree()

assert ls_utils.tracing_is_enabled() is False
with rh.tracing_context(client=client):
_run_test(tracked_test, pytest_request=None, langtest_extra={"cache": None, "cached_hosts": None})

run_tree = seen["run_tree"]
assert run_tree is not None
assert run_tree.id == test_case.run_id
assert run_tree.inputs == {"q": "2+2"}
assert run_tree.outputs == {"a": 4}
assert test_case.inputs == {"q": "2+2"}
# The test's root run was posted to the experiment's project.
client.create_run.assert_called_once()
assert client.create_run.call_args.kwargs["session_name"] == "test-suite"


def test_async_log_functions_work_with_tracking_on_and_tracing_env_unset(monkeypatch, tracing_env_unset):
test_case = _make_tracked_test_case(monkeypatch)
client = MagicMock()
seen = {}

async def tracked_test():
t.log_inputs({"q": "2+2"})
t.log_outputs({"a": 4})
seen["run_tree"] = rh.get_current_run_tree()

with rh.tracing_context(client=client):
asyncio.run(_arun_test(tracked_test, pytest_request=None, langtest_extra={"cache": None, "cached_hosts": None}))

run_tree = seen["run_tree"]
assert run_tree is not None
assert run_tree.id == test_case.run_id
assert run_tree.outputs == {"a": 4}
client.create_run.assert_called_once()


def test_explicitly_disabled_tracing_is_respected(monkeypatch, tracing_env_unset):
_make_tracked_test_case(monkeypatch)
client = MagicMock()
seen = {}

def tracked_test():
seen["run_tree"] = rh.get_current_run_tree()

with rh.tracing_context(client=client, enabled=False):
_run_test(tracked_test, pytest_request=None, langtest_extra={"cache": None, "cached_hosts": None})

assert seen["run_tree"] is None
client.create_run.assert_not_called()