Files
Academic-Affairs-System/tests/Jiaowu.Api.Tests/MoodleCourseClientTests.cs
T

207 lines
12 KiB
C#

using System.Net;
using Jiaowu.Api.Infrastructure.Teaching;
using Microsoft.Extensions.Configuration;
namespace Jiaowu.Api.Tests;
public sealed class MoodleCourseClientTests
{
[Fact]
public async Task CreateCourse_UsesMappedCategoryAndRejectsMissingMapping()
{
var handler = new StubHandler();
var client = Client(handler);
await client.CreateOrRecoverAsync(Guid.NewGuid(), "TASK-1", "课程", CancellationToken.None, 27);
Assert.Contains("courses%5B0%5D%5Bcategoryid%5D=27", handler.Requests.Last());
var before = handler.Requests.Count;
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.CreateOrRecoverAsync(Guid.NewGuid(), "TASK-2", "课程", CancellationToken.None, -1));
Assert.DoesNotContain(handler.Requests.Skip(before), x => x.Contains("core_course_create_courses"));
}
[Fact]
public async Task MatchesExistingIdNumberAndResolvesNumberLinksForEnrolment()
{
var handler = new NumberHandler();
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "token", ["Moodle:CategoryId"] = "4", ["Moodle:StudentRoleId"] = "5"
}).Build();
var client = new MoodleCourseClient(new Factory(new HttpClient(handler)), config);
Assert.Equal("https://moodle.example.edu/sub/course/view.php?id=42", await client.CreateOrRecoverAsync(Guid.NewGuid(), "TASK-1", "课程", CancellationToken.None, -1));
Assert.DoesNotContain(handler.Requests, x => x.Contains("core_course_create_courses"));
await client.SyncStudentsAsync("https://moodle.example.edu/sub/course/view.php?idnumber=TASK-1", ["S01"], CancellationToken.None);
Assert.Contains("enrolments%5B0%5D%5Bcourseid%5D=42", handler.Requests.Last());
await client.SyncStudentsAsync("https://moodle.example.edu/sub/course/view.php?name=CS101&id=99", ["S01"], CancellationToken.None);
Assert.Contains("enrolments%5B0%5D%5Bcourseid%5D=42", handler.Requests.Last());
}
private sealed class NumberHandler : HttpMessageHandler
{
public List<string> Requests { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsStringAsync(cancellationToken);
Requests.Add(body);
var data = body.Contains("field=idnumber") ? "{\"courses\":[{\"id\":42,\"idnumber\":\"TASK-1\"}]}" : body.Contains("value=CS101") ? "{\"courses\":[{\"id\":42,\"shortname\":\"CS101\"}]}" : body.Contains("core_user_get_users_by_field") ? "[{\"id\":7,\"username\":\"S01\"}]" : body.Contains("enrol_manual_enrol_users") ? "null" : "{\"courses\":[]}";
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(data) };
}
}
[Fact]
public async Task StudentImport_ValidatesAllAccountsBeforeEnrollingWithStudentRole()
{
var handler = new TeacherHandler();
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "token", ["Moodle:CategoryId"] = "4", ["Moodle:StudentRoleId"] = "5"
}).Build();
var client = new MoodleCourseClient(new Factory(new HttpClient(handler)), config);
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.SyncStudentsAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01", "missing"], CancellationToken.None));
Assert.Single(handler.Requests);
await client.SyncStudentsAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01"], CancellationToken.None);
Assert.Contains("enrolments%5B0%5D%5Broleid%5D=5", handler.Requests.Last());
}
[Fact]
public async Task CopyCourse_ExcludesUsersAndDoesNotReuseUnknownExistingCourse()
{
var handler = new CopyHandler();
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "token", ["Moodle:CategoryId"] = "4"
}).Build();
var client = new MoodleCourseClient(new Factory(new HttpClient(handler)), config);
Assert.Equal("https://moodle.example.edu/sub/course/view.php?id=42", await client.CopyCourseAsync(Guid.NewGuid(), "TASK-1", "课程", 5, CancellationToken.None));
Assert.Contains("options%5B0%5D%5Bvalue%5D=0", handler.Requests[3]);
handler.HasPartial = true;
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.CopyCourseAsync(Guid.NewGuid(), "TASK-1", "课程", 5, CancellationToken.None));
Assert.Equal(6, handler.Requests.Count);
}
private sealed class CopyHandler : HttpMessageHandler
{
public List<string> Requests { get; } = [];
public bool HasPartial { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsStringAsync(cancellationToken);
Requests.Add(body);
var data = body.Contains("update_courses") ? "null" : body.Contains("duplicate_course") ? "{\"id\":42}" : HasPartial ? "{\"courses\":[{\"id\":42,\"idnumber\":\"\"}]}" : "{\"courses\":[]}";
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(data) };
}
}
[Fact]
public async Task TeacherSync_RequiresAllUsersBeforeEnrolment()
{
var handler = new TeacherHandler();
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "token", ["Moodle:CategoryId"] = "4", ["Moodle:TeacherRoleId"] = "3"
}).Build();
var client = new MoodleCourseClient(new Factory(new HttpClient(handler)), config);
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.SyncTeachersAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01", "MISSING"], CancellationToken.None));
Assert.Single(handler.Requests);
await client.SyncTeachersAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01"], CancellationToken.None);
Assert.Contains("values%5B0%5D=t01", handler.Requests[1]);
Assert.Contains("enrol_manual_enrol_users", handler.Requests.Last());
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.SyncTeachersAsync("https://other.example.edu/sub/course/view.php?id=42", ["T01"], CancellationToken.None));
Assert.Equal(3, handler.Requests.Count);
}
[Fact]
public async Task TeacherSync_RejectsNumbersThatCollideAfterLowercasing()
{
var handler = new TeacherHandler();
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "token", ["Moodle:CategoryId"] = "4", ["Moodle:TeacherRoleId"] = "3"
}).Build();
var client = new MoodleCourseClient(new Factory(new HttpClient(handler)), config);
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.SyncTeachersAsync("https://moodle.example.edu/sub/course/view.php?id=42", ["T01", "t01"], CancellationToken.None));
Assert.Empty(handler.Requests);
}
private sealed class TeacherHandler : HttpMessageHandler
{
public List<string> Requests { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsStringAsync(cancellationToken);
Requests.Add(body);
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body.Contains("core_user_get_users_by_field") ? "[{\"id\":7,\"username\":\"t01\",\"suspended\":0}]" : "null") };
}
}
[Fact]
public async Task CreatesHiddenCourseAndRecoversUsingStableIdentifiers()
{
var taskId = Guid.NewGuid();
var key = "jiaowu-" + taskId.ToString("N");
var handler = new StubHandler();
var client = Client(handler);
var first = await client.CreateOrRecoverAsync(taskId, "TASK-1", "测试课程", CancellationToken.None);
Assert.Equal("https://moodle.example.edu/sub/course/view.php?id=42", first);
Assert.Contains("courses%5B0%5D%5Bvisible%5D=0", handler.Requests[3]);
Assert.Contains("courses%5B0%5D%5Bidnumber%5D=TASK-1", handler.Requests[3]);
handler.ExistingKey = key;
var second = await client.CreateOrRecoverAsync(taskId, "TASK-1", "测试课程", CancellationToken.None);
Assert.Equal(first, second);
Assert.Equal(7, handler.Requests.Count);
}
[Fact]
public async Task RetryRecoversCourseAfterCreateResponseIsLost()
{
var taskId = Guid.NewGuid();
var handler = new StubHandler { FailCreateOnce = true, RecoveryKey = "jiaowu-" + taskId.ToString("N") };
var client = Client(handler);
await Assert.ThrowsAsync<MoodleIntegrationException>(() => client.CreateOrRecoverAsync(taskId, "TASK-1", "课程", CancellationToken.None));
Assert.Equal("https://moodle.example.edu/sub/course/view.php?id=42", await client.CreateOrRecoverAsync(taskId, "TASK-1", "课程", CancellationToken.None));
Assert.Equal(7, handler.Requests.Count);
}
[Fact]
public async Task RejectsExistingCourseWithUnexpectedIdNumber()
{
var handler = new StubHandler { ExistingKey = "different" };
await Assert.ThrowsAsync<MoodleIntegrationException>(() => Client(handler).CreateOrRecoverAsync(Guid.NewGuid(), "TASK-1", "课程", CancellationToken.None));
Assert.Equal(2, handler.Requests.Count);
}
private static MoodleCourseClient Client(StubHandler handler)
{
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
{
["Moodle:BaseUrl"] = "https://moodle.example.edu/sub", ["Moodle:Token"] = "test-token", ["Moodle:CategoryId"] = "4"
}).Build();
return new MoodleCourseClient(new Factory(new HttpClient(handler)), config);
}
private sealed class Factory(HttpClient client) : IHttpClientFactory
{
public HttpClient CreateClient(string name) => client;
}
private sealed class StubHandler : HttpMessageHandler
{
public List<string> Requests { get; } = [];
public string? ExistingKey { get; set; }
public string? RecoveryKey { get; set; }
public bool FailCreateOnce { get; set; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = await request.Content!.ReadAsStringAsync(cancellationToken);
Requests.Add(body);
if (FailCreateOnce && body.Contains("core_course_create_courses"))
{
FailCreateOnce = false;
ExistingKey = RecoveryKey;
throw new HttpRequestException("response lost");
}
var response = body.Contains("jiaowu-copy-") || body.Contains("field=idnumber") ? "{\"courses\":[]}" : body.Contains("core_course_create_courses") ? "[{\"id\":42,\"shortname\":\"x\"}]" :
ExistingKey is null ? "{\"courses\":[]}" : $"{{\"courses\":[{{\"id\":42,\"idnumber\":\"{ExistingKey}\"}}]}}";
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(response) };
}
}
}