196 lines
12 KiB
C#
196 lines
12 KiB
C#
using ClosedXML.Excel;
|
|
using Jiaowu.Api.Controllers;
|
|
using Jiaowu.Api.Domain.Academic;
|
|
using Jiaowu.Api.Domain.Identity;
|
|
using Jiaowu.Api.Infrastructure.Auth;
|
|
using Jiaowu.Api.Infrastructure.Persistence;
|
|
using Jiaowu.Api.Infrastructure.Teaching;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Configuration;
|
|
|
|
namespace Jiaowu.Api.Tests;
|
|
|
|
public sealed class TeachingTaskRosterProfileTests
|
|
{
|
|
[Fact]
|
|
public async Task Assigned_teacher_receives_contact_and_special_fields_in_roster_and_export()
|
|
{
|
|
await using var connection = new SqliteConnection("Data Source=:memory:");
|
|
await connection.OpenAsync();
|
|
var options = new DbContextOptionsBuilder<AppDbContext>()
|
|
.UseSqlite(connection)
|
|
.Options;
|
|
await using var db = new AppDbContext(options);
|
|
await db.Database.EnsureCreatedAsync();
|
|
|
|
var teacherUser = User("T001", "任课教师");
|
|
var studentUser = User("S001", "学生甲");
|
|
var college = new College { Code = "CS", Name = "计算机学院" };
|
|
var major = new Major
|
|
{
|
|
Code = "080901", Name = "计算机科学与技术",
|
|
CollegeId = college.Id, DegreeType = "工学学士"
|
|
};
|
|
var administrativeClass = new AdministrativeClass
|
|
{
|
|
Code = "CS2026-01", Name = "计科一班", MajorId = major.Id, Grade = 2026
|
|
};
|
|
var teacher = new Teacher
|
|
{
|
|
TeacherNumber = "T001", Name = "任课教师", CollegeId = college.Id,
|
|
UserId = teacherUser.Id
|
|
};
|
|
var student = new Student
|
|
{
|
|
StudentNumber = "S001", Name = "学生甲", UserId = studentUser.Id,
|
|
AdministrativeClassId = administrativeClass.Id,
|
|
EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1),
|
|
Phone = "13800000000", Email = "s@example.edu.cn", WeChat = "student-wechat",
|
|
EmergencyContactName = "家长", EmergencyContactRelationship = "母亲",
|
|
EmergencyContactPhone = "13900000000", SpecialTags = "走读",
|
|
SpecialNeeds = "需留意交通延误"
|
|
};
|
|
var term = new AcademicTerm
|
|
{
|
|
Code = "2026-1", Name = "2026-2027-1", AcademicYear = "2026-2027",
|
|
Season = TermSeason.Autumn, StartDate = new DateOnly(2026, 9, 1),
|
|
EndDate = new DateOnly(2027, 1, 20)
|
|
};
|
|
var course = new Course
|
|
{
|
|
Code = "CS101", Name = "程序设计", CollegeId = college.Id,
|
|
Credits = 4, TotalHours = 64, LectureHours = 48, PracticeHours = 16,
|
|
Nature = CourseNature.MajorRequired,
|
|
AssessmentMethod = AssessmentMethod.Examination
|
|
};
|
|
db.AddRange(teacherUser, studentUser, college);
|
|
await db.SaveChangesAsync();
|
|
db.AddRange(major, teacher, term, course);
|
|
await db.SaveChangesAsync();
|
|
db.Add(administrativeClass);
|
|
await db.SaveChangesAsync();
|
|
db.Add(student);
|
|
await db.SaveChangesAsync();
|
|
var task = new TeachingTask
|
|
{
|
|
TaskNumber = "2026-CS101-01", Name = "程序设计教学班",
|
|
AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40,
|
|
Status = TeachingTaskStatus.Published,
|
|
MoodleCourseUrl = "https://moodle.example.edu/course/view.php?id=42",
|
|
Teachers = [new TeachingTaskTeacher { TeacherId = teacher.Id }],
|
|
Classes = [new TeachingTaskClass { AdministrativeClassId = administrativeClass.Id }]
|
|
};
|
|
db.Add(task);
|
|
db.Add(new TeachingTask { TaskNumber = "OTHER", Name = "其他教学班", AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40, Status = TeachingTaskStatus.Published, MoodleCourseUrl = "https://moodle.example.edu/course/view.php?id=99" });
|
|
db.Add(new TeachingTask { TaskNumber = "DRAFT", Name = "草稿教学班", AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40, Status = TeachingTaskStatus.Draft, MoodleCourseUrl = "https://moodle.example.edu/course/view.php?id=100", Classes = [new TeachingTaskClass { AdministrativeClassId = administrativeClass.Id }] });
|
|
var teacherTask = new TeachingTask { TaskNumber = "OWN", Name = "本人教学班", AcademicTermId = term.Id, CourseId = course.Id, Capacity = 40, Status = TeachingTaskStatus.Published, Teachers = [new TeachingTaskTeacher { TeacherId = teacher.Id }] };
|
|
db.Add(teacherTask);
|
|
await db.SaveChangesAsync();
|
|
|
|
var studentController = new CourseSelectionsController(db, new StudentDataScope(studentUser.Id));
|
|
var coursesResult = Assert.IsType<OkObjectResult>(await studentController.GetMyMoodleCourses(term.Id, CancellationToken.None));
|
|
var courses = Assert.IsAssignableFrom<System.Collections.IEnumerable>(coursesResult.Value);
|
|
var ownCourse = Assert.Single(courses.Cast<object>());
|
|
Assert.Equal("https://moodle.example.edu/course/view.php?id=42", Property(ownCourse, "MoodleCourseUrl"));
|
|
|
|
var moodle = new MoodleCourseClient(new UnusedHttpClientFactory(), new ConfigurationBuilder().Build());
|
|
var moodleController = new MoodleCoursesController(db, new TeacherDataScope(teacherUser.Id), moodle);
|
|
var otherTask = await db.TeachingTasks.SingleAsync(x => x.TaskNumber == "OTHER");
|
|
Assert.IsType<ForbidResult>(await moodleController.Create(otherTask.Id, CancellationToken.None));
|
|
Assert.IsType<ForbidResult>(await moodleController.SyncTeachers(otherTask.Id, CancellationToken.None));
|
|
Assert.Equal(502, Assert.IsType<ObjectResult>(await moodleController.Create(teacherTask.Id, CancellationToken.None)).StatusCode);
|
|
Assert.IsType<ForbidResult>(await moodleController.Copy(teacherTask.Id, new MoodleCopyRequest(99), CancellationToken.None));
|
|
Assert.Equal(502, Assert.IsType<ObjectResult>(await moodleController.SyncTeachers(task.Id, CancellationToken.None)).StatusCode);
|
|
|
|
var controller = new CourseSelectionsController(
|
|
db,
|
|
new TeacherDataScope(teacherUser.Id));
|
|
Assert.IsType<NotFoundResult>(await controller.GetTeachingTaskRoster(otherTask.Id, CancellationToken.None));
|
|
var admin = new CourseSelectionsController(db, new SuperAdminDataScope());
|
|
var adminTasks = Assert.IsType<OkObjectResult>(await admin.GetMyTeachingTasks(term.Id, CancellationToken.None));
|
|
Assert.Equal(3, Assert.IsAssignableFrom<System.Collections.IEnumerable>(adminTasks.Value).Cast<object>().Count());
|
|
var adminRoster = Assert.IsType<OkObjectResult>(await admin.GetTeachingTaskRoster(task.Id, CancellationToken.None));
|
|
var adminStudents = Assert.IsAssignableFrom<System.Collections.IEnumerable>(adminRoster.Value!.GetType().GetProperty("Students")!.GetValue(adminRoster.Value));
|
|
Assert.Single(adminStudents.Cast<object>());
|
|
Assert.IsType<OkObjectResult>(await admin.GetTeachingTaskRoster(otherTask.Id, CancellationToken.None));
|
|
Assert.IsType<FileContentResult>(await admin.ExportTeachingTaskRoster(task.Id, CancellationToken.None));
|
|
var rosterResult = Assert.IsType<OkObjectResult>(
|
|
await controller.GetTeachingTaskRoster(task.Id, CancellationToken.None));
|
|
var students = Assert.IsAssignableFrom<System.Collections.IEnumerable>(
|
|
rosterResult.Value!.GetType().GetProperty("Students")!.GetValue(rosterResult.Value));
|
|
var row = Assert.Single(students.Cast<object>());
|
|
Assert.Equal("13800000000", Property(row, "Phone"));
|
|
Assert.Equal("走读", Property(row, "SpecialTags"));
|
|
Assert.Equal("需留意交通延误", Property(row, "SpecialNeeds"));
|
|
|
|
var export = Assert.IsType<FileContentResult>(
|
|
await controller.ExportTeachingTaskRoster(task.Id, CancellationToken.None));
|
|
using var stream = new MemoryStream(export.FileContents);
|
|
using var workbook = new XLWorkbook(stream);
|
|
var sheet = workbook.Worksheet("教学班名单");
|
|
Assert.Equal("联系电话", sheet.Cell(1, 5).GetString());
|
|
Assert.Equal("特殊标记", sheet.Cell(1, 11).GetString());
|
|
Assert.Equal("13800000000", sheet.Cell(2, 5).GetString());
|
|
Assert.Equal("走读", sheet.Cell(2, 11).GetString());
|
|
var headers = Assert.IsType<string[]>(Assert.IsType<OkObjectResult>(controller.RosterExportColumns()).Value);
|
|
Assert.Equal("联系电话", headers[4]);
|
|
var custom = Assert.IsType<FileContentResult>(await controller.ExportTeachingTaskRoster(task.Id, CancellationToken.None, "4,0", "xlsx"));
|
|
using var selected = new XLWorkbook(new MemoryStream(custom.FileContents));
|
|
Assert.Equal("联系电话", selected.Worksheet(1).Cell(1, 1).GetString());
|
|
Assert.Equal("13800000000", selected.Worksheet(1).Cell(2, 1).GetString());
|
|
Assert.IsType<NotFoundResult>(await controller.ExportTeachingTaskRoster(otherTask.Id, CancellationToken.None, "0", "txt"));
|
|
Assert.Equal("学期", sheet.Cell(1, 15).GetString());
|
|
Assert.Equal("计算机学院", sheet.Cell(2, 20).GetString());
|
|
|
|
var csvFile = Assert.IsType<FileContentResult>(await admin.ExportMoodleRoster(task.Id, "English,2026", "英语\"一班", true, "teacher", CancellationToken.None));
|
|
var csv = System.Text.Encoding.UTF8.GetString(csvFile.FileContents).TrimStart('\uFEFF');
|
|
Assert.Contains("\"s001\",\"English,2026\",\"student\",\"英语\"\"一班\"", csv);
|
|
Assert.Contains("\"t001\",\"English,2026\",\"teacher\",\"英语\"\"一班\"", csv);
|
|
Assert.IsType<NotFoundResult>(await controller.ExportMoodleRoster(otherTask.Id, "course", null, false, null, CancellationToken.None));
|
|
Assert.IsType<BadRequestObjectResult>(await admin.ExportMoodleRoster(task.Id, "course", "123", false, null, CancellationToken.None));
|
|
|
|
db.Add(new TeachingTaskClass { TeachingTaskId = teacherTask.Id, AdministrativeClassId = administrativeClass.Id });
|
|
await db.SaveChangesAsync();
|
|
var courseCsv = Assert.IsType<FileContentResult>(await admin.ExportCourseMoodleRoster(course.Id, term.Id, "English2026", true, "teacher", CancellationToken.None));
|
|
var text = System.Text.Encoding.UTF8.GetString(courseCsv.FileContents).TrimStart('\uFEFF');
|
|
Assert.Contains("username,course1,role1,group1,course2,role2,group2", text);
|
|
Assert.Contains("\"s001\",\"English2026\",\"student\",\"教学班 2026-CS101-01\",\"English2026\",\"student\",\"教学班 OWN\"", text);
|
|
Assert.Contains("\"t001\",\"English2026\",\"teacher\",\"教学班 2026-CS101-01\",\"English2026\",\"teacher\",\"教学班 OWN\"", text);
|
|
Assert.DoesNotContain("教学班 DRAFT", text);
|
|
Assert.IsType<ForbidResult>(await controller.ExportCourseMoodleRoster(course.Id, term.Id, "English2026", false, null, CancellationToken.None));
|
|
}
|
|
|
|
private static string? Property(object value, string name) =>
|
|
value.GetType().GetProperty(name)!.GetValue(value)?.ToString();
|
|
|
|
private static ApplicationUser User(string userName, string displayName) => new()
|
|
{
|
|
Id = Guid.NewGuid(), UserName = userName,
|
|
NormalizedUserName = userName.ToUpperInvariant(), DisplayName = displayName
|
|
};
|
|
|
|
private sealed class TeacherDataScope(Guid userId) : ICurrentUserDataScope
|
|
{
|
|
public CurrentUserScope Current { get; } = new(
|
|
userId, "任课教师", null, DataScope.Self,
|
|
new HashSet<string>([SystemRoles.Teacher]));
|
|
}
|
|
|
|
private sealed class StudentDataScope(Guid userId) : ICurrentUserDataScope
|
|
{
|
|
public CurrentUserScope Current { get; } = new(userId, "学生", null, DataScope.Self, new HashSet<string> { SystemRoles.Student });
|
|
}
|
|
|
|
private sealed class SuperAdminDataScope : ICurrentUserDataScope
|
|
{
|
|
public CurrentUserScope Current { get; } = new(Guid.NewGuid(), "管理员", null, DataScope.All, new HashSet<string> { SystemRoles.SuperAdmin });
|
|
}
|
|
|
|
private sealed class UnusedHttpClientFactory : IHttpClientFactory
|
|
{
|
|
public HttpClient CreateClient(string name) => throw new InvalidOperationException("HTTP should not be called");
|
|
}
|
|
}
|