333 lines
15 KiB
C#
333 lines
15 KiB
C#
using System.Text.Json;
|
|
using Jiaowu.Api.Contracts;
|
|
using Jiaowu.Api.Controllers;
|
|
using Jiaowu.Api.Domain.Academic;
|
|
using Jiaowu.Api.Domain.Identity;
|
|
using Jiaowu.Api.Infrastructure.Auth;
|
|
using Jiaowu.Api.Infrastructure.Caching;
|
|
using Jiaowu.Api.Infrastructure.Persistence;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Jiaowu.Api.Tests;
|
|
|
|
public sealed class CounselorDataScopeTests
|
|
{
|
|
[Theory]
|
|
[InlineData(SystemRoles.PhysicalEducationAdmin)]
|
|
[InlineData(SystemRoles.DormitoryAdmin)]
|
|
[InlineData(SystemRoles.MaintenanceAdmin)]
|
|
[InlineData(SystemRoles.StudentAffairsAdmin)]
|
|
public async Task SpecialistAdminCounselor_CourseCatalogExcludesUnrelatedCourses(string specialistRole)
|
|
{
|
|
await using var fixture = await CounselorFixture.CreateAsync();
|
|
var course = await fixture.Db.Courses.SingleAsync();
|
|
fixture.Db.Courses.Add(new Course { Code = "UNRELATED", Name = "其他课程", CollegeId = course.CollegeId,
|
|
Credits = 2, TotalHours = 32, Nature = CourseNature.MajorRequired });
|
|
await fixture.Db.SaveChangesAsync();
|
|
var scope = new CounselorScope(fixture.Scope.Current.UserId, fixture.Scope.Current.CollegeId!.Value, specialistRole);
|
|
var controller = new CoursesController(fixture.Db, scope, NoOpAppCache.Instance);
|
|
var result = await controller.Get(cancellationToken: CancellationToken.None);
|
|
var page = Assert.IsType<CursorPagedResult<object>>(Assert.IsType<OkObjectResult>(result.Result).Value);
|
|
var json = JsonSerializer.Serialize(page.Items);
|
|
Assert.Contains("COURSE-1", json);
|
|
Assert.DoesNotContain("UNRELATED", json);
|
|
}
|
|
[Fact]
|
|
public async Task Counselor_message_scope_contains_only_managed_class_students()
|
|
{
|
|
await using var fixture = await CounselorFixture.CreateAsync();
|
|
var controller = new NotificationsController(fixture.Db, fixture.Scope);
|
|
|
|
var result = await controller.Send(
|
|
new SendMessageRequest("班级通知", "仅发送给所带行政班。"),
|
|
CancellationToken.None);
|
|
|
|
Assert.IsType<OkObjectResult>(result);
|
|
var notification = Assert.Single(await fixture.Db.Notifications.ToListAsync());
|
|
Assert.Equal(fixture.ManagedStudentUser.Id, notification.UserId);
|
|
Assert.Equal(MessageAudienceType.Custom,
|
|
(await fixture.Db.MessageDispatches.SingleAsync()).AudienceType);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Counselor_attendance_access_excludes_unmanaged_tasks_and_students()
|
|
{
|
|
await using var fixture = await CounselorFixture.CreateAsync();
|
|
var controller = new AttendanceController(fixture.Db, fixture.Scope);
|
|
|
|
var tasksResult = Assert.IsType<OkObjectResult>(await controller.GetMyTasks(
|
|
fixture.Term.Id, null, 1, 20, CancellationToken.None));
|
|
var tasks = Assert.IsType<PagedResult<object>>(tasksResult.Value);
|
|
Assert.Equal(1, tasks.Total);
|
|
|
|
var inaccessible = await controller.GetSheets(
|
|
fixture.UnmanagedTask.Id, null, null, null, 1, 20, CancellationToken.None);
|
|
Assert.IsType<NotFoundResult>(inaccessible);
|
|
|
|
var sheetResult = Assert.IsType<OkObjectResult>(await controller.GetSheet(
|
|
fixture.AttendanceSheet.Id, CancellationToken.None));
|
|
var json = JsonSerializer.Serialize(sheetResult.Value);
|
|
Assert.Contains(fixture.ManagedStudent.StudentNumber, json);
|
|
Assert.DoesNotContain(fixture.UnmanagedStudent.StudentNumber, json);
|
|
|
|
var createResult = await controller.CreateSheet(
|
|
new AttendanceSheetRequest(
|
|
fixture.ManagedTask.Id,
|
|
"越权创建",
|
|
DateTime.UtcNow,
|
|
null,
|
|
AttendanceCheckInMethod.Manual,
|
|
null,
|
|
null,
|
|
null,
|
|
null),
|
|
CancellationToken.None);
|
|
Assert.IsType<ForbidResult>(createResult);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(SystemRoles.PhysicalEducationAdmin)]
|
|
[InlineData(SystemRoles.DormitoryAdmin)]
|
|
[InlineData(SystemRoles.MaintenanceAdmin)]
|
|
[InlineData(SystemRoles.StudentAffairsAdmin)]
|
|
public async Task Counselor_grade_access_excludes_unmanaged_tasks_and_students(string specialistRole)
|
|
{
|
|
await using var fixture = await CounselorFixture.CreateAsync();
|
|
var scope = new CounselorScope(fixture.Scope.Current.UserId, fixture.Scope.Current.CollegeId!.Value, specialistRole);
|
|
var controller = new GradesController(fixture.Db, scope);
|
|
|
|
var sheetsResult = Assert.IsType<OkObjectResult>(await controller.GetSheets(
|
|
fixture.Term.Id, null, page: 1, pageSize: 20,
|
|
cancellationToken: CancellationToken.None));
|
|
var sheets = Assert.IsType<PagedResult<object>>(sheetsResult.Value);
|
|
Assert.Equal(1, sheets.Total);
|
|
|
|
var sheetResult = Assert.IsType<OkObjectResult>(await controller.GetSheet(
|
|
fixture.GradeSheet.Id, cancellationToken: CancellationToken.None));
|
|
var json = JsonSerializer.Serialize(sheetResult.Value);
|
|
Assert.Contains(fixture.ManagedStudent.StudentNumber, json);
|
|
Assert.DoesNotContain(fixture.UnmanagedStudent.StudentNumber, json);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Counselor_course_statistics_contains_every_managed_class_in_sheet()
|
|
{
|
|
await using var fixture = await CounselorFixture.CreateAsync();
|
|
var classes = await fixture.Db.AdministrativeClasses
|
|
.OrderBy(x => x.Code)
|
|
.ToListAsync();
|
|
foreach (var administrativeClass in classes)
|
|
{
|
|
administrativeClass.CounselorUserId = fixture.Scope.Current.UserId;
|
|
administrativeClass.CounselorName = fixture.Scope.Current.DisplayName;
|
|
}
|
|
|
|
fixture.Db.CourseGradeStatistics.AddRange(classes.Select((administrativeClass, index) =>
|
|
new CourseGradeStatistic
|
|
{
|
|
CourseId = fixture.ManagedTask.CourseId,
|
|
AcademicTermId = fixture.Term.Id,
|
|
Scope = CourseGradeStatisticScope.AdministrativeClass,
|
|
ScopeEntityId = administrativeClass.Id,
|
|
StudentCount = 1,
|
|
PassedCount = index == 0 ? 1 : 0,
|
|
Below60Count = index == 0 ? 0 : 1,
|
|
From90To100Count = index == 0 ? 1 : 0,
|
|
HighestScore = index == 0 ? 90 : 50,
|
|
AverageScore = index == 0 ? 90 : 50,
|
|
LowestScore = index == 0 ? 90 : 50,
|
|
PassRate = index == 0 ? 100 : 0,
|
|
CalculatedAt = DateTime.UtcNow
|
|
}));
|
|
await fixture.Db.SaveChangesAsync();
|
|
|
|
var controller = new GradesController(fixture.Db, fixture.Scope);
|
|
var result = Assert.IsType<OkObjectResult>(await controller.GetCourseStatistics(
|
|
fixture.GradeSheet.Id, CancellationToken.None));
|
|
using var document = JsonDocument.Parse(JsonSerializer.Serialize(result.Value));
|
|
var visibleClasses = document.RootElement.GetProperty("Classes");
|
|
|
|
Assert.Equal(2, visibleClasses.GetArrayLength());
|
|
Assert.Contains(visibleClasses.EnumerateArray(), item =>
|
|
item.GetProperty("ClassName").GetString() == "所带班级");
|
|
Assert.Contains(visibleClasses.EnumerateArray(), item =>
|
|
item.GetProperty("ClassName").GetString() == "其他班级");
|
|
}
|
|
|
|
private sealed class CounselorScope : ICurrentUserDataScope
|
|
{
|
|
public CounselorScope(Guid userId, Guid collegeId, string specialistRole = SystemRoles.PhysicalEducationAdmin)
|
|
{
|
|
Current = new CurrentUserScope(
|
|
userId,
|
|
"测试辅导员",
|
|
collegeId,
|
|
EffectiveDataScopeResolver.Resolve([SystemRoles.Counselor, specialistRole]),
|
|
new HashSet<string>([SystemRoles.Counselor, specialistRole]));
|
|
}
|
|
|
|
public CurrentUserScope Current { get; }
|
|
}
|
|
|
|
private sealed class CounselorFixture : IAsyncDisposable
|
|
{
|
|
private readonly SqliteConnection connection;
|
|
|
|
private CounselorFixture(
|
|
SqliteConnection connection,
|
|
AppDbContext db,
|
|
ApplicationUser counselor,
|
|
ApplicationUser managedStudentUser,
|
|
Student managedStudent,
|
|
Student unmanagedStudent,
|
|
AcademicTerm term,
|
|
TeachingTask managedTask,
|
|
TeachingTask unmanagedTask,
|
|
AttendanceSheet attendanceSheet,
|
|
GradeSheet gradeSheet,
|
|
Guid collegeId)
|
|
{
|
|
this.connection = connection;
|
|
Db = db;
|
|
ManagedStudentUser = managedStudentUser;
|
|
ManagedStudent = managedStudent;
|
|
UnmanagedStudent = unmanagedStudent;
|
|
Term = term;
|
|
ManagedTask = managedTask;
|
|
UnmanagedTask = unmanagedTask;
|
|
AttendanceSheet = attendanceSheet;
|
|
GradeSheet = gradeSheet;
|
|
Scope = new CounselorScope(counselor.Id, collegeId);
|
|
}
|
|
|
|
public AppDbContext Db { get; }
|
|
public ApplicationUser ManagedStudentUser { get; }
|
|
public Student ManagedStudent { get; }
|
|
public Student UnmanagedStudent { get; }
|
|
public AcademicTerm Term { get; }
|
|
public TeachingTask ManagedTask { get; }
|
|
public TeachingTask UnmanagedTask { get; }
|
|
public AttendanceSheet AttendanceSheet { get; }
|
|
public GradeSheet GradeSheet { get; }
|
|
public CounselorScope Scope { get; }
|
|
|
|
public static async Task<CounselorFixture> CreateAsync()
|
|
{
|
|
var connection = new SqliteConnection("Data Source=:memory:");
|
|
await connection.OpenAsync();
|
|
var db = new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
|
|
.UseSqlite(connection).Options);
|
|
await db.Database.EnsureCreatedAsync();
|
|
|
|
var college = new College { Code = "C01", Name = "测试学院" };
|
|
var major = new Major
|
|
{
|
|
Code = "M01", Name = "测试专业", CollegeId = college.Id,
|
|
DegreeType = "本科", SchoolingYears = 4
|
|
};
|
|
var counselor = User("counselor", "辅导员", college.Id);
|
|
var managedStudentUser = User("student1", "所带学生", college.Id);
|
|
var unmanagedStudentUser = User("student2", "其他学生", college.Id);
|
|
var managedClass = new AdministrativeClass
|
|
{
|
|
Code = "CL01", Name = "所带班级", MajorId = major.Id, Grade = 2026,
|
|
CounselorUserId = counselor.Id, CounselorName = counselor.DisplayName
|
|
};
|
|
var unmanagedClass = new AdministrativeClass
|
|
{
|
|
Code = "CL02", Name = "其他班级", MajorId = major.Id, Grade = 2026
|
|
};
|
|
var managedStudent = Student("20260001", "所带学生", managedClass.Id,
|
|
managedStudentUser.Id);
|
|
var unmanagedStudent = Student("20260002", "其他学生", unmanagedClass.Id,
|
|
unmanagedStudentUser.Id);
|
|
var term = new AcademicTerm
|
|
{
|
|
Code = "2026-A", Name = "2026 秋季", AcademicYear = "2026-2027",
|
|
Season = TermSeason.Autumn, StartDate = new DateOnly(2026, 9, 1),
|
|
EndDate = new DateOnly(2027, 1, 20), IsCurrent = true
|
|
};
|
|
var course = new Course
|
|
{
|
|
Code = "COURSE-1", Name = "测试课程", CollegeId = college.Id,
|
|
Credits = 2, TotalHours = 32, LectureHours = 32, PracticeHours = 0,
|
|
Nature = CourseNature.MajorRequired,
|
|
AssessmentMethod = AssessmentMethod.Examination
|
|
};
|
|
var managedTask = Task("TASK-1", "混合教学班", term.Id, course.Id);
|
|
managedTask.Classes.Add(new TeachingTaskClass
|
|
{ TeachingTaskId = managedTask.Id, AdministrativeClassId = managedClass.Id });
|
|
managedTask.Classes.Add(new TeachingTaskClass
|
|
{ TeachingTaskId = managedTask.Id, AdministrativeClassId = unmanagedClass.Id });
|
|
var unmanagedTask = Task("TASK-2", "无关教学班", term.Id, course.Id);
|
|
unmanagedTask.Classes.Add(new TeachingTaskClass
|
|
{ TeachingTaskId = unmanagedTask.Id, AdministrativeClassId = unmanagedClass.Id });
|
|
var attendanceSheet = new AttendanceSheet
|
|
{
|
|
TeachingTaskId = managedTask.Id,
|
|
Name = "第一周点名",
|
|
AttendanceDate = new DateTime(2026, 9, 1),
|
|
Status = AttendanceSheetStatus.Submitted,
|
|
Records =
|
|
[
|
|
new AttendanceRecord { StudentId = managedStudent.Id, Status = AttendanceStatus.Present },
|
|
new AttendanceRecord { StudentId = unmanagedStudent.Id, Status = AttendanceStatus.Absent }
|
|
]
|
|
};
|
|
var gradeSheet = new GradeSheet
|
|
{
|
|
TeachingTaskId = managedTask.Id,
|
|
Status = GradeSheetStatus.Published,
|
|
Records =
|
|
[
|
|
new GradeRecord { StudentId = managedStudent.Id, TotalScore = 90, IsPassed = true },
|
|
new GradeRecord { StudentId = unmanagedStudent.Id, TotalScore = 50, IsPassed = false }
|
|
]
|
|
};
|
|
|
|
db.AddRange(college, term);
|
|
db.Users.AddRange(counselor, managedStudentUser, unmanagedStudentUser);
|
|
await db.SaveChangesAsync();
|
|
db.AddRange(major, course);
|
|
await db.SaveChangesAsync();
|
|
db.AddRange(managedClass, unmanagedClass);
|
|
await db.SaveChangesAsync();
|
|
db.AddRange(managedStudent, unmanagedStudent, managedTask, unmanagedTask);
|
|
await db.SaveChangesAsync();
|
|
db.AddRange(attendanceSheet, gradeSheet);
|
|
await db.SaveChangesAsync();
|
|
db.ChangeTracker.Clear();
|
|
|
|
return new CounselorFixture(connection, db, counselor, managedStudentUser,
|
|
managedStudent, unmanagedStudent, term, managedTask, unmanagedTask,
|
|
attendanceSheet, gradeSheet, college.Id);
|
|
}
|
|
|
|
private static ApplicationUser User(string name, string displayName, Guid collegeId) => new()
|
|
{
|
|
Id = Guid.NewGuid(), UserName = name, NormalizedUserName = name.ToUpperInvariant(),
|
|
DisplayName = displayName, CollegeId = collegeId, IsEnabled = true
|
|
};
|
|
|
|
private static Student Student(string number, string name, Guid classId, Guid userId) => new()
|
|
{
|
|
StudentNumber = number, Name = name, AdministrativeClassId = classId,
|
|
EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1), UserId = userId
|
|
};
|
|
|
|
private static TeachingTask Task(string number, string name, Guid termId, Guid courseId) => new()
|
|
{
|
|
TaskNumber = number, Name = name, AcademicTermId = termId, CourseId = courseId,
|
|
Capacity = 100, Status = TeachingTaskStatus.Published
|
|
};
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Db.DisposeAsync();
|
|
await connection.DisposeAsync();
|
|
}
|
|
}
|
|
}
|