XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

ChaoXingAutoClass

【WinUI】基于 XFEstudio 的 XFEWinUIApplication 模板重建的 WinUI 3 课程工作台。二维码和账号密码登录、课程 GridView、章节、播放进度、学习笔记及日志均使用原生 WinUI 控件。网页播放器运行在独立后台进程中,界面不显示课程网站。

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json;
using ChaoXingAutoClass.Browser;
using Microsoft.Playwright;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;

namespace ChaoXingAutoClass.Test;

[TestFixture]
public sealed class HomeworkBrowserTests
{
    [Test]
    public async Task HomeworkPaginationPreservesSubmittedAndUnavailableStates()
    {
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Channel = "msedge", Headless = true });
        await using var context = await browser.NewContextAsync(); var page = await context.NewPageAsync();
        await page.RouteAsync("**/*", async route =>
        {
            var url = new Uri(route.Request.Url);
            var html = url.AbsolutePath == "/course" ? "<button onclick=\"document.querySelector('iframe').src='/work/list?page=1'\">作业</button><iframe></iframe>" :
                url.Query.Contains("page=2") ? "<div class=bottomList><ul><li data='/work/task?workId=two'><div class=right-content><p>第二份</p><p class=status>待批阅</p></div></li><li data='/work/task?workId=three'><div class=right-content><p>未开放</p><p class=status>未交</p></div><div class=time>未开始</div></li></ul></div><div id=page><li class='xl-nextPage xl-disabled'></li></div>" :
                "<div class=bottomList><ul><li data='/work/task?workId=one'><div class=right-content><p>第一份</p><p class=status>未交</p></div></li></ul></div><div id=page><li class=xl-nextPage onclick=\"location.href='/work/list?page=2'\"><i></i></li></div><style>#page li{display:block;width:40px;height:40px;background:gray}</style>";
            await route.FulfillAsync(new() { Body = html, ContentType = "text/html; charset=utf-8" });
        });
        await using var adapter = new ChaoxingBrowser(context, page, Network());
        var homework = await adapter.GetHomeworksAsync(new("course", "课程", "http://127.0.0.1:45678/course"), CancellationToken.None);
        Assert.Equal(3, homework.Count); Assert.False(homework[0].Completed); Assert.True(homework[1].Completed); Assert.False(homework[2].Available);
    }
    [Test]
    public async Task VisibleOptionLettersMapToRandomizedInternalValuesAndRemoveOmittedChoices()
    {
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Channel = "msedge", Headless = true });
        await using var context = await browser.NewContextAsync(); var page = await context.NewPageAsync();
        await page.SetContentAsync(Questions);
        await using var adapter = new ChaoxingBrowser(context, page, Network());
        var questions = await adapter.GetQuestionsAsync(Path.GetDirectoryName(adapter.NetworkFile)!, false, CancellationToken.None);
        Assert.Equal(2, questions.Count); Assert.Equal(QuestionKind.Single, questions[0].Kind); Assert.Equal(QuestionKind.Multiple, questions[1].Kind);
        Assert.Equal("B", questions[0].Options[1].Key); Assert.Equal("第二选项", questions[0].Options[1].Text);
        await adapter.ApplyAnswersAsync(questions, [Proposal(questions[0], ["B"]), Proposal(questions[1], ["B", "C"])], CancellationToken.None);
        Assert.Equal("A", await page.Locator("#answerone").InputValueAsync());
        Assert.Equal("AB", await page.Locator("#answertwo").InputValueAsync());
    }
    [Test]
    public async Task TwoCoursePagesWithIdenticalQuestionIdsRemainIndependent()
    {
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Channel = "msedge", Headless = true });
        await using var context = await browser.NewContextAsync(); var a = await context.NewPageAsync(); var b = await context.NewPageAsync();
        await a.SetContentAsync(Questions); await b.SetContentAsync(Questions);
        await using var first = new ChaoxingBrowser(context, a, Network()); await using var second = new ChaoxingBrowser(context, b, Network());
        var firstQuestions = await first.GetQuestionsAsync(Path.GetDirectoryName(first.NetworkFile)!, false, CancellationToken.None);
        var secondQuestions = await second.GetQuestionsAsync(Path.GetDirectoryName(second.NetworkFile)!, false, CancellationToken.None);
        await first.ApplyAnswersAsync([firstQuestions[0]], [Proposal(firstQuestions[0], ["B"])], CancellationToken.None);
        Assert.Equal("A", await a.Locator("#answerone").InputValueAsync()); Assert.Equal("", await b.Locator("#answerone").InputValueAsync());
        await second.ApplyAnswersAsync([secondQuestions[0]], [Proposal(secondQuestions[0], ["A"])], CancellationToken.None);
        Assert.Equal("D", await b.Locator("#answerone").InputValueAsync()); Assert.Equal("A", await a.Locator("#answerone").InputValueAsync());
    }
    [Test]
    public async Task AllMultipleChoicesRemainSelectedWithRandomizedDxValues()
    {
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Channel = "msedge", Headless = true });
        await using var context = await browser.NewContextAsync(); var page = await context.NewPageAsync();
        await page.SetContentAsync(Questions); await page.Locator("#answertwo").EvaluateAsync("e=>e.value=''");
        await using var adapter = new ChaoxingBrowser(context, page, Network());
        var q = (await adapter.GetQuestionsAsync(Path.GetDirectoryName(adapter.NetworkFile)!, false, CancellationToken.None))[1];
        await adapter.ApplyAnswersAsync([q], [Proposal(q, ["A", "B", "C"])], CancellationToken.None);
        Assert.Equal("ABD", await page.Locator("#answertwo").InputValueAsync());
    }
    [Test]
    public async Task ChangedSelectionIsDetectedBeforeSubmission()
    {
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Channel = "msedge", Headless = true });
        await using var context = await browser.NewContextAsync(); var page = await context.NewPageAsync();
        await page.SetContentAsync(Questions);
        await using var adapter = new ChaoxingBrowser(context, page, Network());
        var q = (await adapter.GetQuestionsAsync(Path.GetDirectoryName(adapter.NetworkFile)!, false, CancellationToken.None))[1];
        await adapter.ApplyAnswersAsync([q], [Proposal(q, ["B", "C"])], CancellationToken.None);
        await page.Locator("#answertwo").EvaluateAsync("e=>e.value='D'");
        await Assert.ThrowsAsync<InvalidOperationException>(() => adapter.SubmitAsync([q], CancellationToken.None));
    }
    [Test]
    public void DocumentationExtractionIncludesRelevantSectionBeyondPageIntroduction()
    {
        var text = "intro" + new string('x', 15000) + " typeAliases names must be unique; aliases can share one class. " + new string('y', 15000);
        var excerpt = PublicReferenceProvider.ExtractRelevantText(text, "MyBatis typeAliases");
        Assert.Contains("names must be unique", excerpt); Assert.True(excerpt.Length <= 9000);
    }
    [Test]
    public void RepeatedFrameworkMentionsDoNotCrowdOutSpecificConnectionSource()
    {
        var introduction = string.Concat(Enumerable.Range(0, 18).Select(_ => "MyBatis configuration " + new string('x', 1700)));
        var content = introduction + "POOLED PooledConnection close pushConnection returns the connection to the pool." + new string('y', 12000);
        var excerpt = PublicReferenceProvider.ExtractRelevantText(content, "MyBatis configuration POOLED PooledConnection close pushConnection");
        Assert.Contains("returns the connection to the pool", excerpt); Assert.True(excerpt.Length <= 9000);
    }
    [Test]
    public void DistinctDocumentationTopicsRetainBothCacheScopeAndConnectionLifecycle()
    {
        var content = "MyBatis configuration overview " + new string('x', 13000) +
            "namespace SqlSession flushCache By default just local session caching is enabled; add cache to enable global caching." +
            new string('y', 14000) + "POOLED close PooledConnection returns the connection to the pool." + new string('z', 12000);
        var excerpt = PublicReferenceProvider.ExtractRelevantText(content, "MyBatis configuration namespace SqlSession flushCache POOLED close PooledConnection");
        Assert.Contains("just local session caching", excerpt); Assert.Contains("returns the connection to the pool", excerpt); Assert.True(excerpt.Length <= 9000);
    }
    [Test]
    public void ChineseSearchPhrasesFindRelatedWordsWithoutExactWholePhraseMatch()
    {
        var content = "文档前言" + new string('x', 14000) + "品牌的作用包括帮助企业实施市场细分战略。" + new string('y', 14000);
        var excerpt = PublicReferenceProvider.ExtractRelevantText(content, "品牌作用和企业市场细分战略");
        Assert.Contains("品牌的作用包括帮助企业实施市场细分战略", excerpt); Assert.True(excerpt.Length <= 9000);
    }
    [Test]
    public async Task RealEdgeSkipsAttachmentAndDuplicateDeepSeekOutputThenSubmitsNextHomework()
    {
        using var playwright = await Playwright.CreateAsync();
        await using var browser = await playwright.Chromium.LaunchAsync(new() { Channel = "msedge", Headless = true });
        await using var context = await browser.NewContextAsync(); var page = await context.NewPageAsync();
        var siteSubmissions = 0; var modelRequests = 0;
        await page.RouteAsync("**/*", async route =>
        {
            var url = new Uri(route.Request.Url);
            string html;
            if (url.AbsolutePath == "/course")
                html = "<button onclick=\"document.querySelector('iframe').src='/work/list'\">作业</button><iframe style='width:900px;height:700px'></iframe>";
            else if (url.AbsolutePath == "/work/list")
                html = string.Join("", new[] { "attachment", "duplicate", "good" }.Select(id =>
                    $"<div data-cx-homework data-url='/work/task?workId={id}' data-title='{id}' data-status='{(id == "good" && siteSubmissions > 0 ? "待批阅" : "未交")}'></div>"));
            else if (url.AbsolutePath.EndsWith("/prompt"))
            {
                siteSubmissions++; html = "<div data-cx-result>提交成功</div><div>本次成绩 100 分</div>";
            }
            else
            {
                html = url.Query.Contains("attachment") ? "<div data-cx-question=q data-kind=short><p data-cx-stem>上传实验报告</p><textarea></textarea></div>" :
                    string.Join("", new[] { "q1", "q2" }.Select(id => $"<div data-cx-question={id} data-kind=single><p data-cx-stem>合成选择题{id}</p><input type=radio data-cx-option=A name={id}>选项A</div>"));
                html += "<button data-cx-submit onclick=\"location.href='/work/prompt'\">提交</button>";
            }
            await route.FulfillAsync(new() { ContentType = "text/html; charset=utf-8", Body = html });
        });
        using var http = new HttpClient(new AgentTests.StubHandler(async request =>
        {
            using var payload = JsonDocument.Parse(await request.Content!.ReadAsStringAsync());
            var inputs = payload.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();
            modelRequests++;
            var ids = inputs.Select(q => q.GetProperty("id").GetString()).ToArray();
            var answer = new { summary = "合成响应", answers = ids.Select(id => new {
                questionId = modelRequests == 1 ? ids[0] : id, choices = new[] { "A" }, text = "", confidence = .9,
                grounded = true, explanation = "合成判断", evidence = "合成测试材料"
            }) };
            return AgentTests.Ok(JsonSerializer.Serialize(new { choices = new[] { new { finish_reason = "stop", message = new { content = JsonSerializer.Serialize(answer) } } } }));
        }));
        var settings = new AppSettings { ApiKey = "synthetic-test", VisionEnabled = false, TranscriptionEnabled = false, AutomaticReferences = false };
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "queue-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        var controller = new LearningController(adapter, new DeepSeekAgent(http, settings), settings, directory);
        var course = new CourseInfo("course", "合成课程", "http://127.0.0.1:45678/course");
        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(40));
        await controller.RunAsync([], cancellationToken: timeout.Token, includeHomework: true, course: course);
        Assert.Equal(LearningStatus.Completed, controller.Status); Assert.Equal(2, modelRequests); Assert.Equal(1, siteSubmissions);
        Assert.Equal(new[] { "attachment", "duplicate" }, controller.SkippedTasks.Select(t => t.Id).ToArray());
        var final = await adapter.GetHomeworksAsync(course, timeout.Token);
        Assert.False(final[0].Completed); Assert.False(final[1].Completed); Assert.True(final[2].Completed);
        Assert.True(File.Exists(Path.Combine(directory, "task-skips.json")));
    }

    private static AnswerProposal Proposal(QuestionSnapshot q, string[] choices) => new(q.Id, choices, "", 1, true, "测试", "测试依据");
    private static string Network() => Path.Combine(AppContext.BaseDirectory, "work", Guid.NewGuid().ToString("N"), "network.jsonl");
    private const string Questions = """
        <style>.questionLi{padding:16px}.answerBg{padding:12px;cursor:pointer}</style>
        <div class=TiMu><div class=questionLi typename=单选题 id=one><h3 class=mark_name>选择第二选项</h3><input type=hidden id=answerone name=answerone value="">
          <div role=radio class=answerBg qid=one qtype=0 onclick="answerone.value='D'"><span class=num_option data=D>A</span><div class=answer_p>第一选项</div></div>
          <div role=radio class=answerBg qid=one qtype=0 onclick="answerone.value='A'"><span class=num_option data=A>B</span><div class=answer_p>第二选项</div></div></div>
        <div class=questionLi typename=多选题 id=two><h3 class=mark_name>选择第二、第三项</h3><input type=hidden id=answertwo name=answertwo value=D>
          <div role=checkbox class=answerBg qid=two qtype=1 onclick="toggle('D')"><span class=num_option_dx data=D>A</span><div class=answer_p>第一项</div></div>
          <div role=checkbox class=answerBg qid=two qtype=1 onclick="toggle('A')"><span class=num_option_dx data=A>B</span><div class=answer_p>第二项</div></div>
          <div role=checkbox class=answerBg qid=two qtype=1 onclick="toggle('B')"><span class=num_option_dx data=B>C</span><div class=answer_p>第三项</div></div></div></div>
        <button class=completeBtn role=button>提交</button><script>function toggle(k){answertwo.value=answertwo.value.includes(k)?answertwo.value.replace(k,''):(answertwo.value+k).split('').sort().join('')}</script>
        """;
}