-
-
Notifications
You must be signed in to change notification settings - Fork 631
Expand file tree
/
Copy pathAIToolCallbackAdapterTests.cs
More file actions
368 lines (293 loc) · 13.5 KB
/
AIToolCallbackAdapterTests.cs
File metadata and controls
368 lines (293 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using BotSharp.Abstraction.Conversations.Models;
using BotSharp.Plugin.AgentSkills.Functions;
using Microsoft.Extensions.AI;
using System.Text.Json;
namespace BotSharp.Plugin.AgentSkills.Tests.Functions;
/// <summary>
/// Unit tests for AIToolCallbackAdapter class.
/// Tests requirements: NFR-2.3, FR-4.1, FR-4.2, FR-4.3
/// </summary>
public class AIToolCallbackAdapterTests
{
private readonly Mock<IServiceProvider> _mockServiceProvider;
private readonly Mock<ILogger<AIToolCallbackAdapter>> _mockLogger;
public AIToolCallbackAdapterTests()
{
_mockServiceProvider = new Mock<IServiceProvider>();
_mockLogger = new Mock<ILogger<AIToolCallbackAdapter>>();
}
#region Constructor Tests
[Fact]
public void Constructor_WithNullAIFunction_ThrowsArgumentNullException()
{
var act = () => new AIToolCallbackAdapter(null!, _mockServiceProvider.Object, _mockLogger.Object);
act.Should().Throw<ArgumentNullException>().WithParameterName("aiFunction");
}
[Fact]
public void Constructor_WithNullServiceProvider_ThrowsArgumentNullException()
{
var testFunction = CreateTestFunction("test-tool", "result");
var act = () => new AIToolCallbackAdapter(testFunction, null!, _mockLogger.Object);
act.Should().Throw<ArgumentNullException>().WithParameterName("serviceProvider");
}
[Fact]
public void Constructor_WithNullLogger_DoesNotThrow()
{
var testFunction = CreateTestFunction("test-tool", "result");
var act = () => new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, null);
act.Should().NotThrow("logger is optional");
}
#endregion
#region Property Tests
[Fact]
public void Name_ReturnsAIFunctionName()
{
var expectedName = "test-tool-name";
var testFunction = CreateTestFunction(expectedName, "result");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
adapter.Name.Should().Be(expectedName);
}
[Fact]
public void Provider_ReturnsAgentSkills()
{
var testFunction = CreateTestFunction("test-tool", "result");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
adapter.Provider.Should().Be("AgentSkills");
}
#endregion
#region Successful Execution Tests
[Fact]
public async Task Execute_WithValidArguments_ReturnsSuccessAndSetsContent()
{
var expectedResult = "Test result content";
var testFunction = CreateTestFunction("test-tool", expectedResult);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"param1\": \"value1\"}" };
var result = await adapter.Execute(message);
result.Should().BeTrue();
message.Content.Should().Be(expectedResult);
}
[Fact]
public async Task Execute_WithValidJson_ParsesArgumentsCorrectly()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"skillName\": \"test-skill\", \"filePath\": \"test.txt\"}" };
var result = await adapter.Execute(message);
result.Should().BeTrue();
message.Content.Should().Be("success");
}
[Fact]
public async Task Execute_WithMixedCaseJson_ParsesCaseInsensitively()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"SkillName\": \"test\", \"FILE_PATH\": \"test.txt\"}" };
var result = await adapter.Execute(message);
result.Should().BeTrue();
message.Content.Should().Be("success");
}
#endregion
#region Argument Parsing Error Tests
[Fact]
public async Task Execute_WithInvalidJson_ReturnsFalseAndSetsErrorMessage()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{invalid json" };
var result = await adapter.Execute(message);
result.Should().BeFalse();
message.Content.Should().Contain("Invalid JSON arguments");
}
[Fact]
public async Task Execute_WithEmptyArguments_SucceedsWithEmptyDictionary()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "" };
var result = await adapter.Execute(message);
result.Should().BeTrue();
message.Content.Should().Be("success");
}
[Fact]
public async Task Execute_WithNullArguments_SucceedsWithEmptyDictionary()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = null };
var result = await adapter.Execute(message);
result.Should().BeTrue();
message.Content.Should().Be("success");
}
#endregion
#region Exception Handling Tests
[Fact]
public async Task Execute_WhenFileNotFound_ReturnsFalseWithFriendlyMessage()
{
var exception = new FileNotFoundException("SKILL.md not found");
var testFunction = CreateTestFunctionThatThrows("test-tool", exception);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"skillName\": \"missing-skill\"}" };
var result = await adapter.Execute(message);
result.Should().BeFalse();
message.Content.Should().Contain("Skill or file not found");
message.Content.Should().Contain("SKILL.md not found");
}
[Fact]
public async Task Execute_WhenUnauthorizedAccess_ReturnsFalseWithSecurityMessage()
{
var exception = new UnauthorizedAccessException("Access denied");
var testFunction = CreateTestFunctionThatThrows("test-tool", exception);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"filePath\": \"../../../etc/passwd\"}" };
var result = await adapter.Execute(message);
result.Should().BeFalse();
message.Content.Should().Contain("Access denied");
}
[Fact]
public async Task Execute_WhenFileSizeExceeded_ReturnsFalseWithSizeMessage()
{
var exception = new InvalidOperationException("File size exceeds maximum allowed size of 51200 bytes");
var testFunction = CreateTestFunctionThatThrows("test-tool", exception);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"filePath\": \"large-file.txt\"}" };
var result = await adapter.Execute(message);
result.Should().BeFalse();
message.Content.Should().Contain("File size exceeds limit");
}
[Fact]
public async Task Execute_WhenGenericException_ReturnsFalseWithErrorMessage()
{
var exception = new Exception("Unexpected error occurred");
var testFunction = CreateTestFunctionThatThrows("test-tool", exception);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"param\": \"value\"}" };
var result = await adapter.Execute(message);
result.Should().BeFalse();
message.Content.Should().Contain("Error executing tool");
message.Content.Should().Contain("test-tool");
message.Content.Should().Contain("Unexpected error occurred");
}
#endregion
#region Logging Tests
[Fact]
public async Task Execute_LogsDebugInformation()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{\"param\": \"value\"}" };
await adapter.Execute(message);
_mockLogger.Verify(x => x.Log(
LogLevel.Debug,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("Executing tool")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.AtLeastOnce);
}
[Fact]
public async Task Execute_OnSuccess_LogsInformation()
{
var testFunction = CreateTestFunction("test-tool", "success");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{}" };
await adapter.Execute(message);
_mockLogger.Verify(x => x.Log(
LogLevel.Information,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("executed successfully")),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once);
}
[Fact]
public async Task Execute_OnFileNotFound_LogsWarning()
{
var exception = new FileNotFoundException("File not found");
var testFunction = CreateTestFunctionThatThrows("test-tool", exception);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{}" };
await adapter.Execute(message);
_mockLogger.Verify(x => x.Log(
LogLevel.Warning,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("File not found")),
It.Is<Exception>(ex => ex == exception),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once);
}
[Fact]
public async Task Execute_OnUnauthorizedAccess_LogsError()
{
var exception = new UnauthorizedAccessException("Access denied");
var testFunction = CreateTestFunctionThatThrows("test-tool", exception);
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{}" };
await adapter.Execute(message);
_mockLogger.Verify(x => x.Log(
LogLevel.Error,
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => v.ToString()!.Contains("Unauthorized access")),
It.Is<Exception>(ex => ex == exception),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once);
}
#endregion
#region Edge Case Tests
[Fact]
public async Task Execute_WhenAIFunctionReturnsNull_SetsEmptyContent()
{
var testFunction = CreateTestFunctionReturningNull("test-tool");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{}" };
var result = await adapter.Execute(message);
result.Should().BeTrue();
// When AIFunction returns null, ConvertToString() returns "null" string
message.Content.Should().Be("null");
}
[Fact]
public async Task Execute_WhenAIFunctionReturnsEmptyString_SetsEmptyContent()
{
var testFunction = CreateTestFunction("test-tool", "");
var adapter = new AIToolCallbackAdapter(testFunction, _mockServiceProvider.Object, _mockLogger.Object);
var message = new RoleDialogModel { FunctionArgs = "{}" };
var result = await adapter.Execute(message);
result.Should().BeTrue();
message.Content.Should().BeEmpty();
}
#endregion
#region Helper Methods
/// <summary>
/// Creates a test AIFunction using AIFunctionFactory that returns a specified result.
/// </summary>
private static AIFunction CreateTestFunction(string name, string returnValue)
{
return AIFunctionFactory.Create(
() => returnValue,
name: name,
description: "Test function");
}
/// <summary>
/// Creates a test AIFunction using AIFunctionFactory that throws an exception.
/// </summary>
private static AIFunction CreateTestFunctionThatThrows(string name, Exception exception)
{
return AIFunctionFactory.Create(
() =>
{
throw exception;
#pragma warning disable CS0162 // Unreachable code detected
return "";
#pragma warning restore CS0162 // Unreachable code detected
},
name: name,
description: "Test function that throws");
}
/// <summary>
/// Creates a test AIFunction using AIFunctionFactory that returns null.
/// </summary>
private static AIFunction CreateTestFunctionReturningNull(string name)
{
return AIFunctionFactory.Create(
() => (string?)null,
name: name,
description: "Test function returning null");
}
#endregion
}