using XFEExtension.NetCore.XUnit.Assertions; using XFEExtension.NetCore.XUnit.Attributes; using System.Net; using System.Text; using System.Text.Json; using ChaoXingAutoClass.Core; namespace ChaoXingAutoClass.Test; [TestFixture] public sealed class AgentTests { [TestCase("http://api.deepseek.com")] [TestCase("https://secret@example.com")] [TestCase("https://api.deepseek.com?key=secret")] public void InvalidApiAddressIsRejected(string address) => Assert.Throws(() => new AppSettings { ApiBaseUrl = address }.Validate()); [Test] public void SettingsSerializationExcludesPlainApiKey() { var json = JsonSerializer.Serialize(new AppSettings { ApiKey = "test-secret-do-not-save" }); Assert.False(json.Contains("test-secret-do-not-save")); Assert.False(json.Contains("\"ApiKey\"")); } [Test] public async Task MultimodalRequestUsesConfiguredEndpointAndActualImageBytes() { var directory = Path.Combine(AppContext.BaseDirectory, "work", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(directory); var image = Path.Combine(directory, "question.png"); await File.WriteAllBytesAsync(image, Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=")); string? body = null, url = null, authorization = null; var handler = new StubHandler(async request => { body = await request.Content!.ReadAsStringAsync(); url = request.RequestUri!.ToString(); authorization = request.Headers.Authorization?.ToString(); var answer = """{"summary":"已分析","answers":[{"questionId":"q1","choices":["A"],"text":"","confidence":0.95,"grounded":true,"explanation":"材料明确说明","evidence":"00:10 的课程定义"}]}"""; return Ok(JsonSerializer.Serialize(new { choices = new[] { new { finish_reason = "stop", message = new { content = answer } } } })); }); var settings = new AppSettings { ApiBaseUrl = "http://127.0.0.1:5000/v1", ApiKey = "test-key", Model = "configured-vision-model" }; using var client = new HttpClient(handler); var result = await new DeepSeekAgent(client, settings).AnswerAsync("课程", "00:10 的课程定义:示例", [new("q1", QuestionKind.Single, "DOM 题意", [new("A", "正确")], "f", 0, image, true)], CancellationToken.None); Assert.Equal("http://127.0.0.1:5000/v1/chat/completions", url); Assert.Equal("Bearer test-key", authorization); Assert.Contains("configured-vision-model", body!); Assert.Contains("data:image/png;base64,", body!); Assert.False(body!.Contains("test-key")); using var payload = JsonDocument.Parse(body!); Assert.Equal("enabled", payload.RootElement.GetProperty("thinking").GetProperty("type").GetString()); Assert.True(payload.RootElement.GetProperty("max_tokens").GetInt32() >= 24576); Assert.Equal("A", Assert.Single(result.Answers).Choices.Single()); } [Test] public void InvalidOrTruncatedAgentOutputIsRejected() { Assert.Throws(() => DeepSeekAgent.ParseAnswers("{broken")); Assert.Throws(() => DeepSeekAgent.ParseAnswers("{\"summary\":\"no answers\"}")); } [Test] public void FencedJsonCanBeParsed() { var result = DeepSeekAgent.ParseAnswers("```json\n{\"summary\":\"ok\",\"answers\":[]}\n```"); Assert.Empty(result.Answers); Assert.Equal("ok", result.Summary); } [Test] public async Task InvalidAnswerFormatIsRegeneratedOnceWithoutApplyingAnything() { var calls = 0; using var client = new HttpClient(new StubHandler(_ => { var answer = ++calls == 1 ? "{\"summary\":\"omitted answers\"}" : """{"summary":"ok","answers":[{"questionId":"q","choices":["A"],"text":"","confidence":0.9,"grounded":true,"explanation":"课程依据","evidence":"00:10 定义"}]}"""; return Task.FromResult(Ok(JsonSerializer.Serialize(new { choices = new[] { new { finish_reason = "stop", message = new { content = answer } } } }))); })); var result = await new DeepSeekAgent(client, new AppSettings { ApiKey = "test", VisionEnabled = false, DeepReviewEnabled = true }).AnswerAsync("课程", "定义", [new("q", QuestionKind.Single, "问题", [new("A", "选项")], "f", 0)], CancellationToken.None); Assert.Equal(2, calls); Assert.Equal("A", result.Answers[0].Choices[0]); } [TestCase("X", .99, true, "片段证据")] [TestCase("A", .4, true, "片段证据")] [TestCase("A", .99, false, "片段证据")] [TestCase("A", .99, true, "")] public void UnsupportedOrUngroundedAnswersAreNotApplied(string choice, double confidence, bool grounded, string evidence) { var question = new QuestionSnapshot("q", QuestionKind.Single, "问题", [new("A", "选择")], "f", 0); var answer = new AnswerProposal("q", [choice], "", confidence, grounded, "", evidence); Assert.NotNull(AnswerValidator.Validate([question], [answer], .85)); } [Test] public async Task HttpErrorsDoNotLeakApiKey() { using var client = new HttpClient(new StubHandler(_ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized) { Content = new StringContent("invalid secret-value") }))); var error = await Assert.ThrowsAsync(() => new DeepSeekAgent(client, new AppSettings { ApiKey = "secret-value" }).TestConnectionAsync(CancellationToken.None)); Assert.False(error.Message.Contains("secret-value")); } internal static HttpResponseMessage Ok(string json) => new(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; internal sealed class StubHandler(Func> callback) : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => callback(request); } }