ChaoXingAutoClass
【WinUI】基于 XFEstudio 的 XFEWinUIApplication 模板重建的 WinUI 3 课程工作台。二维码和账号密码登录、课程 GridView、章节、播放进度、学习笔记及日志均使用原生 WinUI 控件。网页播放器运行在独立后台进程中,界面不显示课程网站。
关注
0
Fork
0
Star
0
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;
namespace ChaoXingAutoClass.Test;
[TestFixture]
public sealed class BatchingTests
{
[TestCase(1, 1)]
[TestCase(30, 1)]
[TestCase(31, 2)]
[TestCase(61, 3)]
public async Task OneAnswerCallPerThirtyQuestionsAndOneResearchPassPerPaper(int count, int calls)
{
var observed = new List<int>(); var references = new References();
using var http = new HttpClient(new AgentTests.StubHandler(async request =>
{
var rows = Inputs(await request.Content!.ReadAsStringAsync()); observed.Add(rows.Length);
return AgentTests.Ok(Response(rows));
}));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }, references);
var usage = new List<AgentUsage>(); agent.UsageReceived += usage.Add;
var result = await agent.AnswerAsync("测试作业", "材料", Questions(count), CancellationToken.None);
Assert.Equal(calls, observed.Count); Assert.True(observed.All(n => n is > 0 and <= 30));
Assert.Equal(count, observed.Sum()); Assert.Equal(count, result.Answers.Length); Assert.Equal(count, result.Answers.Select(a => a.QuestionId).Distinct().Count());
Assert.Equal(1, references.Calls); Assert.Equal(calls, usage.Count); Assert.True(usage.All(u => u.Purpose == "answer-initial" && u.TotalTokens == 150));
}
[Test]
public async Task MultipleChoiceReviewIsReturnedInTheSameSingleAnswerCall()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; return AgentTests.Ok(Response(Inputs(await request.Content!.ReadAsStringAsync()))); }));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false });
var q = Questions(1)[0] with { Kind = QuestionKind.Multiple };
var result = await agent.AnswerAsync("多选", "材料", [q], CancellationToken.None);
Assert.Equal(1, calls); Assert.Equal(1, result.Reviews!.Length); Assert.Equal(2, result.Reviews[0].Options.Length);
}
[Test]
public async Task StrictModeUncertainOptionCannotTriggerExtraPaidCallsOrPassReview()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; return AgentTests.Ok(Response(Inputs(await request.Content!.ReadAsStringAsync()), .79)); }));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false, StopOnUncertainAnswers = true });
var q = Questions(1)[0] with { Kind = QuestionKind.Multiple };
await Assert.ThrowsAsync<AnswerEvidenceException>(() => agent.AnswerAsync("多选", "材料", [q], CancellationToken.None));
Assert.Equal(1, calls);
}
[TestCase("low-confidence")]
[TestCase("no-evidence")]
[TestCase("missing-review")]
public async Task DefaultUncertainOptionReturnsOriginalAnswerWithWarningAndOneCall(string issue)
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request =>
{
calls++; var body = JsonNode.Parse(Response(Inputs(await request.Content!.ReadAsStringAsync()), .1))!;
var response = JsonNode.Parse(body["choices"]![0]!["message"]!["content"]!.GetValue<string>())!;
if (issue == "no-evidence") response["reviews"]![0]!["options"]![0]!["evidence"] = "";
if (issue == "missing-review") response.AsObject().Remove("reviews");
body["choices"]![0]!["message"]!["content"] = response.ToJsonString();
return AgentTests.Ok(body.ToJsonString());
}));
var questions = new[] { Questions(1)[0] with { Kind = QuestionKind.Multiple } };
var result = await new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }).AnswerAsync("多选", "材料", questions, CancellationToken.None);
Assert.Equal(1, calls); Assert.Equal(new[] { "A", "B" }, result.Answers[0].Choices); Assert.Equal(.9, result.Answers[0].Confidence);
Assert.True(result.Warnings!.Length > 0);
if (issue != "missing-review") Assert.Equal(.1, result.Reviews![0].Options[0].Confidence);
}
[Test]
public async Task DefaultMalformedResponseStopsWithoutAnotherAnswerRequest()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(_ => { calls++; return Task.FromResult(AgentTests.Ok("{\"choices\":[{\"message\":{\"content\":\"{broken\"}}]}")); }));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false });
await Assert.ThrowsAsync<InvalidOperationException>(() => agent.AnswerAsync("题目", "材料", Questions(1), CancellationToken.None));
Assert.Equal(1, calls);
}
[Test]
public async Task ThirtyMixedQuestionsWithInlineOptionReviewsRemainCompleteInOneCall()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request =>
{
calls++; var body = JsonNode.Parse(Response(Inputs(await request.Content!.ReadAsStringAsync())))!;
var content = body["choices"]![0]!["message"]!;
var result = JsonNode.Parse(content["content"]!.GetValue<string>())!;
foreach (var review in result["reviews"]!.AsArray())
result["answers"]!.AsArray().Single(a => a!["questionId"]!.GetValue<string>() == review!["questionId"]!.GetValue<string>())!["optionReviews"] = review!["options"]!.DeepClone();
result.AsObject().Remove("reviews"); content["content"] = result.ToJsonString();
return AgentTests.Ok(body.ToJsonString());
}));
var questions = Questions(30).Select((q, i) => i >= 20 ? q with { Kind = QuestionKind.Multiple } : q).ToArray();
var result = await new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }).AnswerAsync("整卷", "材料", questions, CancellationToken.None);
Assert.Equal(1, calls); Assert.Equal(30, result.Answers.Length); Assert.Equal(10, result.Reviews!.Length);
Assert.Null(AnswerValidator.Validate(questions, result.Answers, .8));
}
private static QuestionSnapshot[] Questions(int count) => Enumerable.Range(1, count).Select(i => new QuestionSnapshot("q" + i, QuestionKind.Single,
"合成题 " + i, [new("A", "项目一"), new("B", "项目二")], "f", i)).ToArray();
private static JsonElement[] Inputs(string body)
{
using var document = JsonDocument.Parse(body);
return document.RootElement.GetProperty("messages")[1].GetProperty("content").EnumerateArray()
.Where(p => p.GetProperty("type").GetString() == "text").Select(p => p.GetProperty("text").GetString()!)
.Where(t => t.StartsWith('{')).Select(t => JsonDocument.Parse(t).RootElement.Clone()).Where(q => q.TryGetProperty("id", out _)).ToArray();
}
private static string Response(JsonElement[] rows, double optionConfidence = .9)
{
var answer = new
{
summary = "合成完整应答",
answers = rows.Select(q => new { questionId = q.GetProperty("id").GetString(), choices = q.GetProperty("kind").GetString() == "Multiple" ? new[] { "A", "B" } : new[] { "A" }, text = "", confidence = .9, grounded = true, explanation = "题意符合材料", evidence = "合成规范定义" }),
reviews = rows.Where(q => q.GetProperty("kind").GetString() == "Multiple").Select(q => new { questionId = q.GetProperty("id").GetString(), options = new[] { "A", "B" }.Select(key => new { key, selected = true, confidence = optionConfidence, reason = "符合材料", evidence = "合成规范定义" }) })
};
return JsonSerializer.Serialize(new { choices = new[] { new { message = new { content = JsonSerializer.Serialize(answer) } } }, usage = new { prompt_tokens = 100, completion_tokens = 50, total_tokens = 150 } });
}
private sealed class References : ILessonReferenceProvider
{
public int Calls;
public Task<IReadOnlyList<ReferenceSource>> GatherAsync(string chapter, string knowledge, IReadOnlyList<QuestionSnapshot> questions, CancellationToken token)
{ Calls++; return Task.FromResult<IReadOnlyList<ReferenceSource>>([new("合成规范", "https://example.test/spec", "项目一与项目二符合定义。", DateTimeOffset.Now)]); }
}
}
using System.Text.Json;
using System.Text.Json.Nodes;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;
namespace ChaoXingAutoClass.Test;
[TestFixture]
public sealed class BatchingTests
{
[TestCase(1, 1)]
[TestCase(30, 1)]
[TestCase(31, 2)]
[TestCase(61, 3)]
public async Task OneAnswerCallPerThirtyQuestionsAndOneResearchPassPerPaper(int count, int calls)
{
var observed = new List<int>(); var references = new References();
using var http = new HttpClient(new AgentTests.StubHandler(async request =>
{
var rows = Inputs(await request.Content!.ReadAsStringAsync()); observed.Add(rows.Length);
return AgentTests.Ok(Response(rows));
}));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }, references);
var usage = new List<AgentUsage>(); agent.UsageReceived += usage.Add;
var result = await agent.AnswerAsync("测试作业", "材料", Questions(count), CancellationToken.None);
Assert.Equal(calls, observed.Count); Assert.True(observed.All(n => n is > 0 and <= 30));
Assert.Equal(count, observed.Sum()); Assert.Equal(count, result.Answers.Length); Assert.Equal(count, result.Answers.Select(a => a.QuestionId).Distinct().Count());
Assert.Equal(1, references.Calls); Assert.Equal(calls, usage.Count); Assert.True(usage.All(u => u.Purpose == "answer-initial" && u.TotalTokens == 150));
}
[Test]
public async Task MultipleChoiceReviewIsReturnedInTheSameSingleAnswerCall()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; return AgentTests.Ok(Response(Inputs(await request.Content!.ReadAsStringAsync()))); }));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false });
var q = Questions(1)[0] with { Kind = QuestionKind.Multiple };
var result = await agent.AnswerAsync("多选", "材料", [q], CancellationToken.None);
Assert.Equal(1, calls); Assert.Equal(1, result.Reviews!.Length); Assert.Equal(2, result.Reviews[0].Options.Length);
}
[Test]
public async Task StrictModeUncertainOptionCannotTriggerExtraPaidCallsOrPassReview()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request => { calls++; return AgentTests.Ok(Response(Inputs(await request.Content!.ReadAsStringAsync()), .79)); }));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false, StopOnUncertainAnswers = true });
var q = Questions(1)[0] with { Kind = QuestionKind.Multiple };
await Assert.ThrowsAsync<AnswerEvidenceException>(() => agent.AnswerAsync("多选", "材料", [q], CancellationToken.None));
Assert.Equal(1, calls);
}
[TestCase("low-confidence")]
[TestCase("no-evidence")]
[TestCase("missing-review")]
public async Task DefaultUncertainOptionReturnsOriginalAnswerWithWarningAndOneCall(string issue)
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request =>
{
calls++; var body = JsonNode.Parse(Response(Inputs(await request.Content!.ReadAsStringAsync()), .1))!;
var response = JsonNode.Parse(body["choices"]![0]!["message"]!["content"]!.GetValue<string>())!;
if (issue == "no-evidence") response["reviews"]![0]!["options"]![0]!["evidence"] = "";
if (issue == "missing-review") response.AsObject().Remove("reviews");
body["choices"]![0]!["message"]!["content"] = response.ToJsonString();
return AgentTests.Ok(body.ToJsonString());
}));
var questions = new[] { Questions(1)[0] with { Kind = QuestionKind.Multiple } };
var result = await new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }).AnswerAsync("多选", "材料", questions, CancellationToken.None);
Assert.Equal(1, calls); Assert.Equal(new[] { "A", "B" }, result.Answers[0].Choices); Assert.Equal(.9, result.Answers[0].Confidence);
Assert.True(result.Warnings!.Length > 0);
if (issue != "missing-review") Assert.Equal(.1, result.Reviews![0].Options[0].Confidence);
}
[Test]
public async Task DefaultMalformedResponseStopsWithoutAnotherAnswerRequest()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(_ => { calls++; return Task.FromResult(AgentTests.Ok("{\"choices\":[{\"message\":{\"content\":\"{broken\"}}]}")); }));
var agent = new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false });
await Assert.ThrowsAsync<InvalidOperationException>(() => agent.AnswerAsync("题目", "材料", Questions(1), CancellationToken.None));
Assert.Equal(1, calls);
}
[Test]
public async Task ThirtyMixedQuestionsWithInlineOptionReviewsRemainCompleteInOneCall()
{
var calls = 0;
using var http = new HttpClient(new AgentTests.StubHandler(async request =>
{
calls++; var body = JsonNode.Parse(Response(Inputs(await request.Content!.ReadAsStringAsync())))!;
var content = body["choices"]![0]!["message"]!;
var result = JsonNode.Parse(content["content"]!.GetValue<string>())!;
foreach (var review in result["reviews"]!.AsArray())
result["answers"]!.AsArray().Single(a => a!["questionId"]!.GetValue<string>() == review!["questionId"]!.GetValue<string>())!["optionReviews"] = review!["options"]!.DeepClone();
result.AsObject().Remove("reviews"); content["content"] = result.ToJsonString();
return AgentTests.Ok(body.ToJsonString());
}));
var questions = Questions(30).Select((q, i) => i >= 20 ? q with { Kind = QuestionKind.Multiple } : q).ToArray();
var result = await new DeepSeekAgent(http, new AppSettings { ApiKey = "synthetic", VisionEnabled = false }).AnswerAsync("整卷", "材料", questions, CancellationToken.None);
Assert.Equal(1, calls); Assert.Equal(30, result.Answers.Length); Assert.Equal(10, result.Reviews!.Length);
Assert.Null(AnswerValidator.Validate(questions, result.Answers, .8));
}
private static QuestionSnapshot[] Questions(int count) => Enumerable.Range(1, count).Select(i => new QuestionSnapshot("q" + i, QuestionKind.Single,
"合成题 " + i, [new("A", "项目一"), new("B", "项目二")], "f", i)).ToArray();
private static JsonElement[] Inputs(string body)
{
using var document = JsonDocument.Parse(body);
return document.RootElement.GetProperty("messages")[1].GetProperty("content").EnumerateArray()
.Where(p => p.GetProperty("type").GetString() == "text").Select(p => p.GetProperty("text").GetString()!)
.Where(t => t.StartsWith('{')).Select(t => JsonDocument.Parse(t).RootElement.Clone()).Where(q => q.TryGetProperty("id", out _)).ToArray();
}
private static string Response(JsonElement[] rows, double optionConfidence = .9)
{
var answer = new
{
summary = "合成完整应答",
answers = rows.Select(q => new { questionId = q.GetProperty("id").GetString(), choices = q.GetProperty("kind").GetString() == "Multiple" ? new[] { "A", "B" } : new[] { "A" }, text = "", confidence = .9, grounded = true, explanation = "题意符合材料", evidence = "合成规范定义" }),
reviews = rows.Where(q => q.GetProperty("kind").GetString() == "Multiple").Select(q => new { questionId = q.GetProperty("id").GetString(), options = new[] { "A", "B" }.Select(key => new { key, selected = true, confidence = optionConfidence, reason = "符合材料", evidence = "合成规范定义" }) })
};
return JsonSerializer.Serialize(new { choices = new[] { new { message = new { content = JsonSerializer.Serialize(answer) } } }, usage = new { prompt_tokens = 100, completion_tokens = 50, total_tokens = 150 } });
}
private sealed class References : ILessonReferenceProvider
{
public int Calls;
public Task<IReadOnlyList<ReferenceSource>> GatherAsync(string chapter, string knowledge, IReadOnlyList<QuestionSnapshot> questions, CancellationToken token)
{ Calls++; return Task.FromResult<IReadOnlyList<ReferenceSource>>([new("合成规范", "https://example.test/spec", "项目一与项目二符合定义。", DateTimeOffset.Now)]); }
}
}