添加四则运算工具

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-06-17 12:22:02 +08:00
co-authored by Claude
parent 2c4d4af070
commit 249227ef0a
5 changed files with 335 additions and 8 deletions
+52
View File
@@ -0,0 +1,52 @@
package calculator
import (
"strings"
"testing"
)
func TestEvaluateBasicArithmetic(t *testing.T) {
tests := []struct {
expression string
want float64
}{
{expression: "1+2*3", want: 7},
{expression: "(1+2)*3", want: 9},
{expression: "12.5*(3+4)/2", want: 43.75},
{expression: "-2 + 3", want: 1},
{expression: "84)÷3", want: 4},
}
for _, tt := range tests {
got, err := Evaluate(tt.expression)
if err != nil {
t.Fatalf("Evaluate(%q) error: %v", tt.expression, err)
}
if got != tt.want {
t.Fatalf("Evaluate(%q) = %v, want %v", tt.expression, got, tt.want)
}
}
}
func TestEvaluateErrors(t *testing.T) {
for _, expression := range []string{"1/0", "1+", "(1+2", "2^3"} {
if _, err := Evaluate(expression); err == nil {
t.Fatalf("Evaluate(%q) expected error", expression)
}
}
}
func TestToolDefinitionAndExecuteTool(t *testing.T) {
definition := ToolDefinition("custom calculator")
if definition.Function == nil || definition.Function.Name != ToolName || definition.Function.Description != "custom calculator" {
t.Fatalf("unexpected definition: %#v", definition)
}
text, err := ExecuteTool(`{"expression":"12.5*(3+4)/2","reason":"用户询问计算结果"}`)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"计算器工具结果", "12.5*(3+4)/2", "43.75", "用户询问计算结果"} {
if !strings.Contains(text, want) {
t.Fatalf("tool result missing %q:\n%s", want, text)
}
}
}