forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBraveTextSearchTests.cs
More file actions
433 lines (367 loc) · 19.1 KB
/
BraveTextSearchTests.cs
File metadata and controls
433 lines (367 loc) · 19.1 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// Copyright (c) Microsoft. All rights reserved.
#pragma warning disable CS0618 // ITextSearch is obsolete
#pragma warning disable CS8602 // Dereference of a possibly null reference - for LINQ expression properties
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Data;
using Microsoft.SemanticKernel.Plugins.Web.Brave;
using Xunit;
namespace SemanticKernel.Plugins.UnitTests.Web.Brave;
public sealed class BraveTextSearchTests : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="BraveTextSearchTests"/> class.
/// </summary>
public BraveTextSearchTests()
{
this._messageHandlerStub = new MultipleHttpMessageHandlerStub();
this._httpClient = new HttpClient(this._messageHandlerStub, disposeHandler: false);
this._kernel = new Kernel();
}
[Fact]
public void AddBraveTextSearchSucceeds()
{
// Arrange
var builder = Kernel.CreateBuilder();
// Act
builder.AddBraveTextSearch(apiKey: "ApiKey");
var kernel = builder.Build();
// Assert
Assert.IsType<BraveTextSearch>(kernel.Services.GetRequiredService<ITextSearch>());
}
[Fact]
public async Task SearchReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", new() { Top = 10, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(10, resultList.Count);
foreach (var stringResult in resultList)
{
Assert.NotEmpty(stringResult);
}
}
[Fact]
public async Task GetTextSearchResultsReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 10, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(10, resultList.Count);
foreach (var textSearchResult in resultList)
{
Assert.NotNull(textSearchResult.Name);
Assert.NotNull(textSearchResult.Value);
Assert.NotNull(textSearchResult.Link);
}
}
[Fact]
public async Task GetSearchResultsReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
KernelSearchResults<object> result = await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 10, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(10, resultList.Count);
foreach (BraveWebPage webPage in resultList.Cast<BraveWebPage>())
{
Assert.NotNull(webPage.Title);
Assert.NotNull(webPage.Description);
Assert.NotNull(webPage.Url);
}
}
[Fact]
public async Task SearchWithCustomStringMapperReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, StringMapper = new TestTextSearchStringMapper() });
// Act
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", new() { Top = 10, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(10, resultList.Count);
foreach (var stringResult in resultList)
{
Assert.NotEmpty(stringResult);
var webPage = JsonSerializer.Deserialize<BraveWebResult>(stringResult);
Assert.NotNull(webPage);
}
}
[Fact]
public async Task GetTextSearchResultsWithCustomResultMapperReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, ResultMapper = new TestTextSearchResultMapper() });
// Act
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 10, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(10, resultList.Count);
foreach (var textSearchResult in resultList)
{
Assert.NotNull(textSearchResult);
Assert.Equal(textSearchResult.Name, textSearchResult.Name?.ToUpperInvariant());
Assert.Equal(textSearchResult.Value, textSearchResult.Value?.ToUpperInvariant());
Assert.Equal(textSearchResult.Link, textSearchResult.Link?.ToUpperInvariant());
}
}
//https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&&country=US&search_lang=en&ui_lang=en-US&safesearch=moderate&text_decorations=True&spellcheck=False&result_filter=web&units=imperial&extra_snippets=True
[Theory]
[InlineData("country", "US", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&country=US")]
[InlineData("search_lang", "en", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&search_lang=en")]
[InlineData("ui_lang", "en-US", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&ui_lang=en-US")]
[InlineData("safesearch", "off", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&safesearch=off")]
[InlineData("safesearch", "moderate", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&safesearch=moderate")]
[InlineData("safesearch", "strict", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&safesearch=strict")]
[InlineData("text_decorations", true, "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&text_decorations=True")]
[InlineData("spellcheck", false, "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&spellcheck=False")]
[InlineData("result_filter", "web", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&result_filter=web")]
[InlineData("units", "imperial", "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&units=imperial")]
[InlineData("extra_snippets", true, "https://api.search.brave.com/res/v1/web/search?q=What%20is%20the%20Semantic%20Kernel%3F&count=5&offset=0&extra_snippets=True")]
public async Task BuildsCorrectUriForEqualityFilterAsync(string paramName, object paramValue, string requestLink)
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(SiteFilterSkResponseJson));
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
TextSearchOptions searchOptions = new() { Top = 5, Skip = 0, Filter = new TextSearchFilter().Equality(paramName, paramValue) };
var result = await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", searchOptions);
// Assert
var requestUris = this._messageHandlerStub.RequestUris;
Assert.Single(requestUris);
Assert.NotNull(requestUris[0]);
Assert.Equal(requestLink, requestUris[0]!.AbsoluteUri);
}
[Fact]
public async Task DoesNotBuildsUriForInvalidQueryParameterAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(SiteFilterSkResponseJson));
TextSearchOptions searchOptions = new() { Top = 5, Skip = 0, Filter = new TextSearchFilter().Equality("fooBar", "Baz") };
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act && Assert
var e = await Assert.ThrowsAsync<ArgumentException>(async () => await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", searchOptions));
Assert.Equal("Unknown equality filter clause field name 'fooBar', must be one of country,search_lang,ui_lang,safesearch,text_decorations,spellcheck,result_filter,units,extra_snippets (Parameter 'searchOptions')", e.Message);
}
[Fact]
public async Task DoesNotBuildsUriForQueryParameterNullInputAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(SiteFilterSkResponseJson));
TextSearchOptions searchOptions = new() { Top = 5, Skip = 0, Filter = new TextSearchFilter().Equality("country", null!) };
// Create an ITextSearch instance using Brave search
var textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act && Assert
var e = await Assert.ThrowsAsync<ArgumentException>(async () => await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", searchOptions));
Assert.Equal("Unknown equality filter clause field name 'country', must be one of country,search_lang,ui_lang,safesearch,text_decorations,spellcheck,result_filter,units,extra_snippets (Parameter 'searchOptions')", e.Message);
}
/// <inheritdoc/>
public void Dispose()
{
this._messageHandlerStub.Dispose();
this._httpClient.Dispose();
GC.SuppressFinalize(this);
}
#region Generic ITextSearch<BraveWebPage> Interface Tests
[Fact]
public async Task LinqSearchAsyncReturnsResultsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
ITextSearch<BraveWebPage> textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
var searchOptions = new TextSearchOptions<BraveWebPage>
{
Top = 4,
Skip = 0
};
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", searchOptions);
// Assert - Verify basic generic interface functionality
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotEmpty(resultList);
// Verify the request was made correctly
var requestUris = this._messageHandlerStub.RequestUris;
Assert.Single(requestUris);
Assert.NotNull(requestUris[0]);
Assert.Contains("count=4", requestUris[0].AbsoluteUri);
}
[Fact]
public async Task LinqGetSearchResultsAsyncReturnsResultsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
ITextSearch<BraveWebPage> textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
var searchOptions = new TextSearchOptions<BraveWebPage>
{
Top = 3,
Skip = 0
};
KernelSearchResults<BraveWebPage> result = await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", searchOptions);
// Assert - Verify generic interface returns results
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotEmpty(resultList);
// Results are now strongly typed as BraveWebPage
// Verify the request was made correctly
var requestUris = this._messageHandlerStub.RequestUris;
Assert.Single(requestUris);
Assert.NotNull(requestUris[0]);
Assert.Contains("count=3", requestUris[0].AbsoluteUri);
}
[Fact]
public async Task LinqGetTextSearchResultsAsyncReturnsResultsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
ITextSearch<BraveWebPage> textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
var searchOptions = new TextSearchOptions<BraveWebPage>
{
Top = 5,
Skip = 0
};
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", searchOptions);
// Assert - Verify generic interface returns TextSearchResult objects
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotEmpty(resultList);
Assert.All(resultList, item => Assert.IsType<TextSearchResult>(item));
// Verify the request was made correctly
var requestUris = this._messageHandlerStub.RequestUris;
Assert.Single(requestUris);
Assert.NotNull(requestUris[0]);
Assert.Contains("count=5", requestUris[0].AbsoluteUri);
}
[Fact]
public async Task CollectionContainsFilterThrowsNotSupportedExceptionAsync()
{
// Arrange - Tests both Enumerable.Contains (C# 13-) and MemoryExtensions.Contains (C# 14+)
// The same code array.Contains() resolves differently based on C# language version:
// - C# 13 and earlier: Enumerable.Contains (LINQ extension method)
// - C# 14 and later: MemoryExtensions.Contains (span-based optimization due to "first-class spans")
// Our implementation handles both identically since Brave API has limited query operators
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
ITextSearch<BraveWebPage> textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
string[] sites = ["microsoft.com", "github.com"];
// Act & Assert - Verify that collection Contains pattern throws clear exception
var searchOptions = new TextSearchOptions<BraveWebPage>
{
Top = 5,
Skip = 0,
Filter = page => sites.Contains(page.Url!.ToString()) // Enumerable.Contains (C# 13-) or MemoryExtensions.Contains (C# 14+)
};
var exception = await Assert.ThrowsAsync<NotSupportedException>(async () =>
{
await textSearch.SearchAsync("test", searchOptions);
});
// Assert - Verify error message explains the limitation clearly
Assert.Contains("Collection Contains filters", exception.Message);
Assert.Contains("not supported", exception.Message);
}
[Fact]
public async Task StringContainsStillWorksWithLINQFiltersAsync()
{
// Arrange - Verify that String.Contains (instance method) still works
// String.Contains is NOT affected by C# 14 "first-class spans" - only arrays are
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSkResponseJson));
ITextSearch<BraveWebPage> textSearch = new BraveTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act - String.Contains should continue to work
var searchOptions = new TextSearchOptions<BraveWebPage>
{
Top = 5,
Skip = 0,
Filter = page => page.Title.Contains("Kernel") // String.Contains - instance method
};
KernelSearchResults<string> result = await textSearch.SearchAsync("Semantic Kernel tutorial", searchOptions);
// Assert - Verify String.Contains works correctly
var requestUris = this._messageHandlerStub.RequestUris;
Assert.Single(requestUris);
Assert.NotNull(requestUris[0]);
Assert.Contains("Kernel", requestUris[0].AbsoluteUri);
Assert.Contains("count=5", requestUris[0].AbsoluteUri);
}
#endregion
#region private
private const string WhatIsTheSkResponseJson = "./TestData/brave_what_is_the_semantic_kernel.json";
private const string SiteFilterSkResponseJson = "./TestData/brave_site_filter_what_is_the_semantic_kernel.json";
private readonly MultipleHttpMessageHandlerStub _messageHandlerStub;
private readonly HttpClient _httpClient;
private readonly Kernel _kernel;
/// <summary>
/// Test mapper which converts a BraveWebPage search result to a string using JSON serialization.
/// </summary>
private sealed class TestTextSearchStringMapper : ITextSearchStringMapper
{
/// <inheritdoc />
public string MapFromResultToString(object result)
{
return JsonSerializer.Serialize(result);
}
}
/// <summary>
/// Test mapper which converts a BraveWebPage search result to a string using JSON serialization.
/// </summary>
private sealed class TestTextSearchResultMapper : ITextSearchResultMapper
{
/// <inheritdoc />
public TextSearchResult MapFromResultToTextSearchResult(object result)
{
if (result is not BraveWebResult webPage)
{
throw new ArgumentException("Result must be a BraveWebResult", nameof(result));
}
return new TextSearchResult(webPage.Description?.ToUpperInvariant() ?? string.Empty)
{
Name = webPage.Title?.ToUpperInvariant(),
Link = webPage.Url?.ToUpperInvariant(),
};
}
}
#endregion
}