ChaoXingAutoClass
【WinUI】基于 XFEstudio 的 XFEWinUIApplication 模板重建的 WinUI 3 课程工作台。二维码和账号密码登录、课程 GridView、章节、播放进度、学习笔记及日志均使用原生 WinUI 控件。网页播放器运行在独立后台进程中,界面不显示课程网站。
关注
0
Fork
0
Star
0
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<ArgumentException>(() => 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<InvalidOperationException>(() => DeepSeekAgent.ParseAnswers("{broken"));
Assert.Throws<InvalidOperationException>(() => 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<HttpRequestException>(() => 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<HttpRequestMessage, Task<HttpResponseMessage>> callback) : HttpMessageHandler
{ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => callback(request); }
}
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<ArgumentException>(() => 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<InvalidOperationException>(() => DeepSeekAgent.ParseAnswers("{broken"));
Assert.Throws<InvalidOperationException>(() => 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<HttpRequestException>(() => 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<HttpRequestMessage, Task<HttpResponseMessage>> callback) : HttpMessageHandler
{ protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => callback(request); }
}