云库增加 AI识图,缓存,我的云库收藏增加安全标志
调用外部API 扣费
This commit is contained in:
1 parent
7c29e57623
commit
150e8644b7
49 files changed
+1069
-28
No files matched your search
@@ -56,6 +56,77 @@ Reject(() => GoodsViolationService.ValidateAndGroup([new() { GoodsId = 1, Reason
|
||||
// SQL generation only: no database connection or production data access.
|
||||
using var db = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql,
|
||||
"Server=127.0.0.1;Database=checks;User Id=unused;Password=unused").Build();
|
||||
// 在内存库验证真实的收藏更新语句和用户隔离,不连接配置中的商品库。
|
||||
using (var favoriteDb = new FreeSql.FreeSqlBuilder()
|
||||
.UseConnectionString(FreeSql.DataType.Sqlite, "Data Source=:memory:;Max Pool Size=1").Build())
|
||||
{
|
||||
favoriteDb.CodeFirst.SyncStructure<UserGoodsFavoriteEntity>();
|
||||
favoriteDb.Insert(new[] { "alice", "bob" }.Select(name => new UserGoodsFavoriteEntity
|
||||
{ UserName = name, GoodsId = 123, CreatedAt = DateTime.Now }).ToArray()).ExecuteAffrows();
|
||||
var serviceTypeForFavorites = typeof(IUserFavoritesService).Assembly.GetType("Store.Modules.CloudProduct.Services.UserFavoritesService")!;
|
||||
using var searchContext = new PluginContext("CloudProduct", "Plugins/CloudProduct", new HostingEnvironment());
|
||||
var indexType = typeof(IUserFavoritesIndexService).Assembly.GetType("Store.Modules.CloudProduct.Services.UserFavoritesIndexService")!;
|
||||
var index = (IUserFavoritesIndexService)Activator.CreateInstance(indexType, searchContext, null)!;
|
||||
var indexName = searchContext.Configuration["Search:FavoritesIndexName"]!;
|
||||
IApiCallDetails? call = null;
|
||||
void Respond(string body, int status = 200)
|
||||
{
|
||||
var settings = new ConnectionSettings(new SingleNodeConnectionPool(new Uri("http://localhost:9200")),
|
||||
new InMemoryConnection(Encoding.UTF8.GetBytes(body), status)).DefaultIndex(indexName)
|
||||
.DisableDirectStreaming().OnRequestCompleted(details => call = details);
|
||||
indexType.GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(index, new OpenSearchClient(settings));
|
||||
}
|
||||
Respond("""{"result":"updated","_shards":{"successful":1,"failed":0}}""");
|
||||
var favorites = (IUserFavoritesService)Activator.CreateInstance(serviceTypeForFavorites,
|
||||
new Store.Modules.CloudProduct.Repositorys.UserGoodsFavoriteRepository(favoriteDb), null, null, index, null, new LocalFavoritesLock(searchContext))!;
|
||||
foreach (var safe in new[] { true, false, false })
|
||||
{
|
||||
await favorites.SaveProductSafetyAsync(new() { UserName = "alice", ProductId = "123", IsSafe = safe });
|
||||
using var update = JsonDocument.Parse(call!.RequestBodyInBytes);
|
||||
Check(update.RootElement.GetProperty("doc").GetProperty("is_safe").GetBoolean() == safe &&
|
||||
Uri.UnescapeDataString(call.Uri.AbsolutePath).EndsWith("/_update/alice:123") && call.Uri.Query.Contains("refresh=wait_for"),
|
||||
"Refresh the matching document after a partial safety update");
|
||||
var rows = favoriteDb.Select<UserGoodsFavoriteEntity>().ToList().ToDictionary(x => x.UserName);
|
||||
Check(rows["alice"].IsSafe == safe && rows["bob"].IsSafe == null, "Safety updates only the matching favorite");
|
||||
}
|
||||
Reject(() => favorites.SaveProductSafetyAsync(new() { UserName = "alice", ProductId = "999", IsSafe = true }).GetAwaiter().GetResult());
|
||||
Respond("""{"error":{"type":"document_missing_exception","reason":"missing"},"status":404}""", 404);
|
||||
Reject(() => favorites.SaveProductSafetyAsync(new() { UserName = "alice", ProductId = "123", IsSafe = true }).GetAwaiter().GetResult());
|
||||
Check(favoriteDb.Select<UserGoodsFavoriteEntity>().Where(x => x.UserName == "alice").First().IsSafe == false, "Roll back on index failure");
|
||||
Respond("""{"hits":{"total":{"value":12,"relation":"eq"},"hits":[{"_source":{"goods_id":123,"is_safe":false}}]}}""");
|
||||
var page = await favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = 2, PageIndex = 2, PageSize = 10 });
|
||||
using var query = JsonDocument.Parse(call!.RequestBodyInBytes);
|
||||
var filters = query.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter");
|
||||
Check(filters.EnumerateArray().Any(f => f.GetProperty("term").TryGetProperty("is_safe", out var term) &&
|
||||
!term.GetProperty("value").GetBoolean()) && query.RootElement.GetProperty("from").GetInt32() == 10,
|
||||
"Apply safety filter inside paged OpenSearch query");
|
||||
Check(page.Total == 12 && page.List.Single().IsSafe == false, "Read safety and filtered total from index");
|
||||
Respond("""{"hits":{"total":{"value":1,"relation":"eq"},"hits":[{"_source":{"goods_id":123}}]}}""");
|
||||
var jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
|
||||
var omitted = JsonSerializer.Deserialize<UserFavoritesSearchRequest>("""{"userName":"alice"}""", jsonOptions)!;
|
||||
await favorites.SearchFavoritesAsync(omitted);
|
||||
using var allQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
|
||||
Check(allQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter").GetArrayLength() == 1,
|
||||
"Omitting status applies only the user filter");
|
||||
await favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = 0 });
|
||||
using var zeroQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
|
||||
Check(zeroQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter").GetArrayLength() == 1, "Status 0 includes all");
|
||||
await favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = 1 });
|
||||
using var safeQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
|
||||
Check(safeQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter").EnumerateArray()
|
||||
.Any(f => f.GetProperty("term").TryGetProperty("is_safe", out var term) && term.GetProperty("value").GetBoolean()), "Status 1 selects safe");
|
||||
foreach (int invalid in new[] { -1, 4 })
|
||||
Reject(() => favorites.SearchFavoritesAsync(new() { UserName = "alice", Status = invalid }).GetAwaiter().GetResult());
|
||||
var uncheckedRequest = JsonSerializer.Deserialize<UserFavoritesSearchRequest>("""{"userName":"alice","status":3}""", jsonOptions)!;
|
||||
var uninspected = await favorites.SearchFavoritesAsync(uncheckedRequest);
|
||||
using var missingQuery = JsonDocument.Parse(call!.RequestBodyInBytes);
|
||||
var missingFilters = missingQuery.RootElement.GetProperty("query").GetProperty("bool").GetProperty("filter");
|
||||
Check(missingFilters.GetArrayLength() == 2 && missingFilters.EnumerateArray().Any(f => f.TryGetProperty("bool", out var clause)
|
||||
&& clause.GetProperty("must_not")[0].GetProperty("exists").GetProperty("field").GetString() == "is_safe"),
|
||||
"Status 3 selects missing safety values alongside the user filter");
|
||||
Check(uninspected.List.Single().IsSafe == null, "Missing safety remains null");
|
||||
Check(favoriteDb.Select<UserGoodsFavoriteEntity>().Count() == 2, "Safety reports never create favorites");
|
||||
}
|
||||
var sql = db.Select<GoodsEntity>().As("g")
|
||||
.Where(x => x.Status == 0 && x.IsSegmented == 0)
|
||||
.Where("NOT EXISTS (SELECT 1 FROM goods_violation v WHERE v.goods_id = g.goods_id)")
|
||||
@@ -129,3 +200,10 @@ await TestDelete(200, """{"errors":true,"items":[{"delete":{"_index":"goods","_i
|
||||
await TestDelete(200, """{"errors":true,"items":[{"delete":{"_index":"goods","_id":"123","status":429,"error":{"type":"rejected","reason":"busy"}}}]}""", true);
|
||||
await TestDelete(200, """{"errors":false,"items":[]}""", true);
|
||||
Console.WriteLine($"PASS: {checks} checks (no external services accessed)");
|
||||
|
||||
// SQLite 检查独占内存库,无需获取 MySQL 会话锁。
|
||||
sealed class LocalFavoritesLock(PluginContext context) : GoodsIndexLock(context), IAsyncDisposable
|
||||
{
|
||||
public override Task<IAsyncDisposable> AcquireFavoritesAsync() => Task.FromResult<IAsyncDisposable>(this);
|
||||
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
}
|
||||
Reference in new issue
Block a user