Skip to content

Commit 2fb489b

Browse files
test(tools): add unit test for using class method as tool
1 parent 12bf10a commit 2fb489b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

tests-integ/test_method_tools.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Test script for class-method-based tools
4+
"""
5+
6+
import logging
7+
from typing import Optional
8+
9+
from strands import Agent, tool
10+
11+
logging.getLogger("strands").setLevel(logging.DEBUG)
12+
logging.basicConfig(format="%(levelname)s | %(name)s | %(message)s", handlers=[logging.StreamHandler()])
13+
14+
15+
class TestAgent:
16+
def __init__(self):
17+
self.agent = None
18+
19+
@tool
20+
def word_counter(self, text: str) -> str:
21+
"""
22+
Count words in text.
23+
24+
Args:
25+
text: Text to analyze
26+
"""
27+
count = len(text.split())
28+
return f"Word count: {count}"
29+
30+
@tool(name="count_chars", description="Count characters in text")
31+
def count_chars(self, text: str, include_spaces: Optional[bool] = True) -> str:
32+
"""
33+
Count characters in text.
34+
35+
Args:
36+
text: Text to analyze
37+
include_spaces: Whether to include spaces in the count
38+
"""
39+
if not include_spaces:
40+
text = text.replace(" ", "")
41+
return f"Character count: {len(text)}"
42+
43+
def initialize_agent(self, tools=None) -> None:
44+
self.agent = Agent(tools=tools or [])
45+
46+
def get_agent(self) -> Agent:
47+
if not self.agent:
48+
self.agent = Agent()
49+
return self.agent
50+
51+
52+
# Object test agent class
53+
test_agent = TestAgent()
54+
# Initialize agent where tools are defined as class methods
55+
test_agent.initialize_agent([test_agent.word_counter, test_agent.count_chars])
56+
# Get the initialized agent
57+
agent = test_agent.get_agent()
58+
59+
print("\n===== Testing Direct Tool Access =====")
60+
# Use the tools directly
61+
word_result = agent.tool.word_counter(text="Hello world, this is a test")
62+
print(f"\nWord counter result: {word_result}")
63+
64+
char_result = agent.tool.count_chars(text="Hello world!", include_spaces=False)
65+
print(f"\nCharacter counter result: {char_result}")
66+
67+
print("\n===== Testing Natural Language Access =====")
68+
# Use through natural language
69+
nl_result = agent("Count the words in this sentence: 'The quick brown fox jumps over the lazy dog'")
70+
print(f"\nNL Result: {nl_result}")

0 commit comments

Comments
 (0)