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

ChaoXingAutoClass

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

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

namespace ChaoXingAutoClass.Test;

[TestFixture]
public sealed class BrowserIntegrationTests
{
    [Test]
    public async Task CourseDocumentReadsEveryRealPageAndUsesNormalReaderScroll()
    {
        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(new() { ViewportSize = new() { Width = 1280, Height = 900 } });
        var page = await context.NewPageAsync();
        await page.RouteAsync("**/*", route =>
        {
            var path = new Uri(route.Request.Url).AbsolutePath;
            var html = path == "/study" ? "<iframe style='width:1000px;height:650px' src='/ananas/modules/pdf/index.html'></iframe>" :
                path.Contains("/modules/pdf/") ? "<iframe style='width:900px;height:550px' src='/screen/v2/file_document'></iframe>" : """
                <style>body{margin:0}li{list-style:none;margin:0;padding:0}img{display:block}</style>
                <input hidden id=fileInfoNameInput value='课件标题'>
                <li id=anchor1><img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='500'%3E%3Ctext x='30' y='50'%3EPage 1%3C/text%3E%3C/svg%3E"></li>
                <li id=anchor2><img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='500'%3E%3Ctext x='30' y='50'%3EPage 2%3C/text%3E%3C/svg%3E"></li>
                <li id=anchor3><img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='800' height='500'%3E%3Ctext x='30' y='50'%3EPage 3%3C/text%3E%3C/svg%3E"></li>
                <script>var naturallyFinished=false;addEventListener('scroll',()=>{if(scrollY>=document.documentElement.scrollHeight-innerHeight-100)naturallyFinished=true});</script>
                """;
            return route.FulfillAsync(new() { ContentType = "text/html; charset=utf-8", Body = html });
        });
        await page.GotoAsync("http://127.0.0.1:45123/study");
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "documents-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        var document = Assert.Single(await adapter.GetDocumentsAsync(CancellationToken.None));
        Assert.Equal("课件标题", document.Title); Assert.Equal(3, document.PageCount);
        var screen = page.Frames.Single(f => f.Url.Contains("/screen/"));
        await adapter.ReadDocumentPageAsync(document, 1, directory, CancellationToken.None);
        Assert.False(await screen.EvaluateAsync<bool>("naturallyFinished"));
        await adapter.ReadDocumentPageAsync(document, 2, directory, CancellationToken.None);
        var last = await adapter.ReadDocumentPageAsync(document, 3, directory, CancellationToken.None);
        await screen.WaitForFunctionAsync("naturallyFinished");
        Assert.Equal(3, Directory.GetFiles(directory, "document-*.png").Length);
        Assert.Contains("第 3 / 3 页", last.Label!);
    }
    [Test]
    public async Task UnrelatedScreenOutsideCoursePdfIsNotADocumentTask()
    {
        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("<li id=anchor1><img src='data:image/svg+xml,%3Csvg/%3E'></li>");
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "not-document-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        Assert.Empty(await adapter.GetDocumentsAsync(CancellationToken.None));
    }
    [Test]
    public async Task ServerCompletionRequiresMatchingActualVideoAttachment()
    {
        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("**/*", route => route.FulfillAsync(new()
        {
            ContentType = "text/html", Body = new Uri(route.Request.Url).AbsolutePath == "/study" ? """
                <script>var mArg={attachments:[{type:'video',objectId:'passed',isPassed:true},{type:'video',objectId:'pending',isPassed:false}]};</script>
                <iframe src="/ananas/modules/video/index.html?objectid=passed"></iframe>
                <iframe src="/ananas/modules/video/index.html?objectid=pending"></iframe>
                <iframe objectid="passed" src="/ananas/modules/video/index.html?v=4"></iframe>
                <iframe objectid="pending" src="/ananas/modules/video/index.html?objectid=passed"></iframe>
                <iframe objectid="unrelated" src="/ananas/modules/video/index.html?v=4"></iframe>
                """ : "<video title='actual attachment'></video>"
        }));
        await page.GotoAsync("http://127.0.0.1:3000/study");
        var directory = Path.Combine(AppContext.BaseDirectory, "work", Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        var videos = await adapter.GetVideosAsync(CancellationToken.None);
        Assert.Equal(5, videos.Count);
        Assert.True(videos[0].ServerCompleted); Assert.True(videos[0].Finished); Assert.False(videos[0].Ended);
        Assert.False(videos[1].ServerCompleted); Assert.False(videos[1].Finished);
        Assert.True(videos[2].ServerCompleted); Assert.False(videos[2].Ended);
        Assert.False(videos[3].ServerCompleted); Assert.False(videos[4].ServerCompleted);
    }
    [TestCase("第1次作答\n本次成绩 83.3 分\n共3题", 83.3)]
    [TestCase("本次得分:暂未公布;单题33.3分", null)]
    public void ReadsActualTotalScoreWithoutSummingQuestionMarks(string text, double? score) => Assert.Equal(score, ChaoxingBrowser.ParseScore(text));
    [Test]
    public void ReadsStandaloneHomeworkPromptScore() => Assert.Equal(80d, ChaoxingBrowser.ParseScore("作业\n80分\n提交时间:10-16 00:40\n查看详情\n重做"));
    [Test]
    public async Task HomeworkPromptNavigationConfirmsActualSubmissionAndScore()
    {
        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("**/*", route => route.FulfillAsync(new() { ContentType = "text/html; charset=utf-8",
            Body = route.Request.Url.Contains("/work/prompt") ? "<div>作业</div><div>100分</div><p>提交时间:10-16 00:40</p><a>查看详情</a><a>重做</a>" :
                "<div data-cx-question=q data-kind=single><div data-cx-stem>试题</div><button data-cx-option=A>选项</button></div><button data-cx-submit onclick=\"location.href='/mooc-ans/mooc2/work/prompt'\">提交</button>" }));
        await page.GotoAsync("http://127.0.0.1:45678/start");
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "prompt-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        var questions = await adapter.GetQuestionsAsync(directory, false, CancellationToken.None);
        var result = await adapter.SubmitAsync(questions, CancellationToken.None);
        Assert.True(result.Confirmed); Assert.Equal(100d, result.Score);
    }
    [Test]
    public async Task EmptyHiddenAuditionAudioCannotPrecedeActualCourseVideo()
    {
        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("<audio id='auditionAudio' src='' hidden></audio><video title='真实课程播放器'></video>");
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "media-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        var video = Assert.Single(await adapter.GetVideosAsync(CancellationToken.None));
        Assert.Equal("真实课程播放器", video.Title);
        Assert.Equal(1, video.Index);
    }

    [Test]
    public async Task SubmissionConfirmsVisibleDialogAndChecksResultArea()
    {
        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("""
            <div data-cx-result>待完成</div>
            <div data-cx-question="q" data-kind="single"><p data-cx-stem>文本出现“已完成”也不是提交结果</p>
            <button data-cx-option="A">选项 A</button></div>
            <button data-cx-submit onclick="document.querySelector('[role=dialog]').style.display='block'">提交</button>
            <div role="dialog" style="display:none">确认提交本次测验?
            <button onclick="document.querySelector('[data-cx-result]').innerText='已提交';this.parentElement.style.display='none'">确定</button></div>
            """);
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "confirm-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        var questions = await adapter.GetQuestionsAsync(directory, false, CancellationToken.None);
        var result = await adapter.SubmitAsync(questions, CancellationToken.None);
        Assert.True(result.Confirmed, result.Message);
        Assert.Equal("已提交", await page.Locator("[data-cx-result]").InnerTextAsync());
    }

    [Test]
    public async Task ChapterSwitchWaitsForNewTaskFrameInsteadOfOldVideo()
    {
        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 == "/study" ? """
                <div id="curtwo" class="posCatalog_select"><button class="posCatalog_name"
                onclick="setTimeout(()=>document.querySelector('iframe').src='/mooc-ans/knowledge/cards?knowledgeid=two',700)">第二节</button></div>
                <iframe src="/mooc-ans/knowledge/cards?knowledgeid=one"></iframe>
                """ : $"<title>{(url.Query.Contains("two") ? "two" : "one")}</title><video></video>";
            await route.FulfillAsync(new() { ContentType = "text/html; charset=utf-8", Body = html });
        });
        await page.GotoAsync("http://127.0.0.1:54321/study?chapterId=one");
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "race-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        await adapter.OpenChapterAsync(new("two", "第二节"), CancellationToken.None);
        Assert.Equal("two", Assert.Single(await adapter.GetVideosAsync(CancellationToken.None)).Title);
    }

    [Test]
    public async Task RealEdgePlaysVideoReadsNestedFramesAndSubmitsDemoQuiz()
    {
        await using var fixture = new DemoSiteHost(); await fixture.StartAsync();
        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(new() { ViewportSize = new() { Width = 1440, Height = 1000 } });
        var page = await context.NewPageAsync();
        var directory = Path.Combine(AppContext.BaseDirectory, "work", "browser-" + Guid.NewGuid().ToString("N"));
        await using var adapter = new ChaoxingBrowser(context, page, Path.Combine(directory, "network.jsonl"));
        await page.GotoAsync(fixture.BaseUrl);
        var course = Assert.Single(await adapter.GetCoursesAsync(CancellationToken.None));
        Assert.Equal("demo", course.Id);
        await adapter.OpenCourseAsync(course, CancellationToken.None);
        var chapter = Assert.Single(await adapter.GetChaptersAsync(CancellationToken.None));
        var notices = new List<string>();
        var controller = new LearningController(adapter, new DemoLearningAgent(), new AppSettings { FrameIntervalSeconds = 5, FramesPerAnalysis = 2 }, directory, TimeSpan.FromMilliseconds(400));
        controller.Notice += notice => notices.Add(notice.Message);
        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(50));
        await controller.RunAsync([chapter], cancellationToken: timeout.Token);
        Assert.True(controller.Status == LearningStatus.Completed, string.Join(Environment.NewLine, notices));
        Assert.Equal(1, fixture.ConfirmedSubmissions);
        Assert.True(Directory.GetFiles(directory, "question-*.png", SearchOption.AllDirectories).Length > 0);
        Assert.True(Directory.GetFiles(directory, "frame-*.jpg", SearchOption.AllDirectories).Length > 0);
        Assert.Contains("品牌", controller.CurrentSummary);
        Assert.Empty(await adapter.GetQuestionsAsync(directory, false, CancellationToken.None));
        await page.ScreenshotAsync(new() { Path = Path.Combine(directory, "complete.png"), FullPage = true });
    }

    [TestCase("https://i.chaoxing.com/base", true)]
    [TestCase("https://mooc1.chaoxing.com/mycourse/studentstudy", true)]
    [TestCase("https://chaoxing.com.attacker.example/path", false)]
    [TestCase("http://i.chaoxing.com/base", false)]
    [TestCase("file:///C:/private", false)]
    public void CourseNavigationStaysWithinConfiguredSite(string url, bool allowed) => Assert.Equal(allowed, ChaoxingBrowser.IsAllowedUrl(url));
}