LangGraph 테스트
LangGraph 테스트 (Test)
LangGraph 에이전트를 프로토타이핑한 다음 자연스럽게 떠오르는 다음 단계가 테스트 작성이에요. 이 가이드는 유닛 테스트를 쓸 때 유용한 몇 가지 패턴을 다뤄요. 참고로 이 가이드는 LangGraph 특유의 내용이라, 커스텀 구조를 가진 그래프 시나리오를 중심으로 해요. 처음 시작하는 경우라면 LangChain의 내장 create_agent를 쓰는 테스트 가이드를 먼저 보는 게 좋아요.
출처: 공식문서
사전 준비 (Prerequisites)
먼저 pytest가 설치돼 있는지 확인해요.
$ pip install -U pytest
시작하기
많은 LangGraph 에이전트가 상태(state)에 의존하기 때문에, 테스트에서 쓸 때마다 그래프를 만든 다음 새 checkpointer 인스턴스로 컴파일하는 패턴이 유용해요. 아래 예시는 node1과 node2를 지나가는 단순한 선형 그래프가 어떻게 동작하는지 보여줘요. 각 노드는 단일 상태 키 my_key를 갱신해요.
import pytest
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
def create_graph() -> StateGraph:
class MyState(TypedDict):
my_key: str
graph = StateGraph(MyState)
graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
graph.add_edge(START, "node1")
graph.add_edge("node1", "node2")
graph.add_edge("node2", END)
return graph
def test_basic_agent_execution() -> None:
checkpointer = MemorySaver()
graph = create_graph()
compiled_graph = graph.compile(checkpointer=checkpointer)
result = compiled_graph.invoke(
{"my_key": "initial_value"},
config={"configurable": {"thread_id": "1"}}
)
assert result["my_key"] == "hello from node2"
개별 노드와 엣지 테스트하기
컴파일된 LangGraph 에이전트는 각 개별 노드에 대한 참조를 graph.nodes로 노출해요. 이 점을 활용하면 에이전트 안의 개별 노드를 따로 테스트할 수 있어요. 단, 이 방식은 그래프 컴파일 시 넘겨준 체크포인터를 우회한다는 점을 기억하세요.
import pytest
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
def create_graph() -> StateGraph:
class MyState(TypedDict):
my_key: str
graph = StateGraph(MyState)
graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
graph.add_edge(START, "node1")
graph.add_edge("node1", "node2")
graph.add_edge("node2", END)
return graph
def test_individual_node_execution() -> None:
# Will be ignored in this example
checkpointer = MemorySaver()
graph = create_graph()
compiled_graph = graph.compile(checkpointer=checkpointer)
# Only invoke node 1
result = compiled_graph.nodes["node1"].invoke(
{"my_key": "initial_value"},
)
assert result["my_key"] == "hello from node1"
부분 실행 (Partial execution)
더 큰 그래프로 이루어진 에이전트라면 전체 흐름을 처음부터 끝까지 돌리기보다, 에이전트 안의 일부 실행 경로만 테스트하고 싶을 때가 있어요. 어떤 경우에는 그 섹션들을 서브그래프로 재구성해서 통상적으로 격리 호출하는 게 의미상 맞을 수 있어요. 하지만 에이전트 그래프의 전체 구조를 바꾸고 싶지 않다면, LangGraph의 영속화(persistence) 메커니즘을 활용해 원하는 섹션이 시작되기 직전에 일시 정지된 상태를 흉내 낼 수 있어요. 절차는 다음과 같아요.
- 체크포인터로 에이전트를 컴파일해요. (테스트에는 인메모리 체크포인터
MemorySaver로 충분해요.) - 테스트를 시작하려는 바로 앞 노드의 이름을
as_node파라미터로 지정해update_state메서드를 호출해요. - 상태를 갱신할 때 쓴 것과 같은
thread_id로 에이전트를 호출하고, 멈추고 싶은 노드의 이름을interrupt_after로 지정해요.
선형 그래프에서 두 번째·세 번째 노드만 실행하는 예시를 볼게요.
import pytest
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
def create_graph() -> StateGraph:
class MyState(TypedDict):
my_key: str
graph = StateGraph(MyState)
graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
graph.add_node("node3", lambda state: {"my_key": "hello from node3"})
graph.add_node("node4", lambda state: {"my_key": "hello from node4"})
graph.add_edge(START, "node1")
graph.add_edge("node1", "node2")
graph.add_edge("node2", "node3")
graph.add_edge("node3", "node4")
graph.add_edge("node4", END)
return graph
def test_partial_execution_from_node2_to_node3() -> None:
checkpointer = MemorySaver()
graph = create_graph()
compiled_graph = graph.compile(checkpointer=checkpointer)
compiled_graph.update_state(
config={
"configurable": {
"thread_id": "1"
}
},
# The state passed into node 2 - simulating the state at
# the end of node 1
values={"my_key": "initial_value"},
# Update saved state as if it came from node 1
# Execution will resume at node 2
as_node="node1",
)
result = compiled_graph.invoke(
# Resume execution by passing None
None,
config={"configurable": {"thread_id": "1"}},
# Stop after node 3 so that node 4 doesn't run
interrupt_after="node3",
)
assert result["my_key"] == "hello from node3"
더 알아보기 (Learn more)
- LangChain 내장
create_agent테스트 가이드 - LangGraph 체크포인터와 영속화 문서
- LangGraph Studio와 테스트·디버깅 워크플로