Add integration tests for graceful handling of nonexistent and partially existing models in search

- Introduced new test cases to validate the behavior of the search handler when querying with nonexistent models, ensuring it returns appropriate error messages without panicking.
- Added a test for scenarios where only some of the requested models exist, confirming that the search can still succeed with valid models while handling errors gracefully.
- Updated the search handler to improve error handling by checking for model existence before proceeding with the search, enhancing robustness in search operations.
This commit is contained in:
Max 2025-12-18 12:20:20 +08:00
parent 19153ee4a5
commit 1d965420ad
2 changed files with 49 additions and 3 deletions

View file

@ -98,8 +98,8 @@ func (h *Handler) SearchWithContext(ctx *agentContext.Context, req *types.Reques
schemas := make([]map[string]interface{}, 0, len(modelIDs))
for _, modelID := range modelIDs {
mod := model.Select(modelID)
if mod == nil {
mod, err := model.Get(modelID)
if err != nil {
continue // Skip non-existent models
}
models[modelID] = mod
@ -196,7 +196,7 @@ func (h *Handler) SearchWithContext(ctx *agentContext.Context, req *types.Reques
primaryModel := models[primaryModelID]
if primaryModel == nil {
primaryModel = model.Select(primaryModelID)
primaryModel, _ = model.Get(primaryModelID) // May be nil, that's ok
}
// 6. Convert records to ResultItems

View file

@ -137,6 +137,52 @@ func TestHandler_Search_Integration(t *testing.T) {
}
}
})
t.Run("search_nonexistent_model_graceful", func(t *testing.T) {
h := db.NewHandler("builtin", nil)
req := &types.Request{
Type: types.SearchTypeDB,
Query: "查询文章",
Source: types.SourceAuto,
Models: []string{"nonexistent_model", "article", "fake_model"},
Limit: 10,
}
// Should NOT panic, should return gracefully with error
result, err := h.SearchWithContext(ctx, req)
require.NoError(t, err)
require.NotNil(t, result)
// Should have error message about no valid models
assert.Equal(t, types.SearchTypeDB, result.Type)
assert.Equal(t, "no valid models found", result.Error)
assert.Empty(t, result.Items)
})
t.Run("search_mixed_models_partial_exist", func(t *testing.T) {
h := db.NewHandler("builtin", nil)
req := &types.Request{
Type: types.SearchTypeDB,
Query: "查询角色",
Source: types.SourceAuto,
Models: []string{"nonexistent_model", "__yao.role", "fake_model"}, // Only __yao.role exists
Limit: 10,
}
// Should NOT panic, should work with the existing model
result, err := h.SearchWithContext(ctx, req)
require.NoError(t, err)
require.NotNil(t, result)
// Should succeed with partial models
assert.Equal(t, types.SearchTypeDB, result.Type)
if result.Error == "" {
// If no error, should have results from __yao.role
assert.GreaterOrEqual(t, len(result.Items), 0)
}
})
}
// newTestContext creates a test context with required fields