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

160 lines
10 KiB
C#

using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Infrastructure.Assessments;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Tests;
public sealed class ComprehensiveAssessmentsControllerTests
{
[Fact]
public async Task Calculation_UsesPublishedSnapshotsAndApprovedDeclarations()
{
await using var fixture = await Fixture.CreateAsync(includeSecondStudent: true);
fixture.Db.StudentAcademicTermStatistics.AddRange(
new StudentAcademicTermStatistic
{
StudentId = fixture.Student.Id, AcademicTermId = fixture.Term.Id,
CourseCount = 6, WeightedAverageScore = 80, AverageScore = 79,
CalculatedAt = DateTime.UtcNow
},
new StudentAcademicTermStatistic
{
StudentId = fixture.OtherStudent!.Id, AcademicTermId = fixture.Term.Id,
CourseCount = 6, WeightedAverageScore = 90, AverageScore = 89,
CalculatedAt = DateTime.UtcNow
});
fixture.Db.ComprehensiveAssessmentDeclarations.Add(new ComprehensiveAssessmentDeclaration
{
ComprehensiveAssessmentBatchId = fixture.Batch.Id,
StudentId = fixture.Student.Id,
ComprehensiveAssessmentDimensionId = fixture.DeclarationDimension.Id,
Title = "省级竞赛", Category = "学科竞赛", Level = "省级",
OccurredOn = new DateOnly(2026, 10, 1), ClaimedScore = 20,
ApprovedScore = 20, Status = ComprehensiveAssessmentDeclarationStatus.Approved
});
await fixture.Db.SaveChangesAsync();
await new ComprehensiveAssessmentCalculationProcessor(fixture.Db)
.ProcessAsync(fixture.Batch.Id, CancellationToken.None);
fixture.Db.ChangeTracker.Clear();
var result = await fixture.Db.ComprehensiveAssessmentResults.Include(x => x.Details)
.SingleAsync(x => x.StudentId == fixture.Student.Id);
var other = await fixture.Db.ComprehensiveAssessmentResults
.SingleAsync(x => x.StudentId == fixture.OtherStudent.Id);
Assert.Equal(56m, result.TotalScore);
Assert.Equal(54m, other.TotalScore);
Assert.Equal(1, result.ClassRank);
Assert.Equal(2, other.ClassRank);
Assert.Equal(2, result.Details.Count);
Assert.Equal(ComprehensiveAssessmentCalculationStatus.Succeeded,
(await fixture.Db.ComprehensiveAssessmentBatches.FindAsync(fixture.Batch.Id))!.CalculationStatus);
}
[Fact]
public async Task CounselorPendingDeclarations_IsLimitedToAssignedClasses()
{
await using var fixture = await Fixture.CreateAsync(includeSecondStudent: true, secondClass: true);
fixture.Db.ComprehensiveAssessmentDeclarations.AddRange(
Declaration(fixture.Batch.Id, fixture.Student.Id, fixture.DeclarationDimension.Id, "本班材料"),
Declaration(fixture.Batch.Id, fixture.OtherStudent!.Id, fixture.DeclarationDimension.Id, "其他班材料"));
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.CounselorScope);
var response = Assert.IsType<OkObjectResult>(await controller.PendingDeclarations(CancellationToken.None));
var items = Assert.IsAssignableFrom<IEnumerable<AssessmentDeclarationView>>(response.Value).ToList();
Assert.Single(items);
Assert.Equal("本班材料", items[0].Title);
}
[Fact]
public async Task StudentCannotAppealOutsidePublicityPeriod()
{
await using var fixture = await Fixture.CreateAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.StudentScope);
var response = await controller.CreateAppeal(
new ComprehensiveAssessmentAppealRequest(fixture.Batch.Id, null, "分数有误"),
CancellationToken.None);
Assert.IsType<ConflictObjectResult>(response);
}
private static ComprehensiveAssessmentDeclaration Declaration(Guid batchId, Guid studentId, Guid dimensionId, string title) => new()
{
ComprehensiveAssessmentBatchId = batchId, StudentId = studentId,
ComprehensiveAssessmentDimensionId = dimensionId, Title = title,
Category = "志愿服务", Level = "校级", OccurredOn = new DateOnly(2026, 10, 1),
ClaimedScore = 5, Status = ComprehensiveAssessmentDeclarationStatus.Submitted,
SubmittedAt = DateTime.UtcNow
};
private sealed class Fixture : IAsyncDisposable
{
private readonly SqliteConnection connection;
public AppDbContext Db { get; }
public Student Student { get; }
public Student? OtherStudent { get; }
public AcademicTerm Term { get; }
public ComprehensiveAssessmentBatch Batch { get; }
public ComprehensiveAssessmentDimension DeclarationDimension { get; }
public ICurrentUserDataScope CounselorScope { get; }
public ICurrentUserDataScope StudentScope { get; }
private Fixture(SqliteConnection connection, AppDbContext db, Student student,
Student? otherStudent, AcademicTerm term, ComprehensiveAssessmentBatch batch,
ComprehensiveAssessmentDimension declarationDimension, Guid counselorId)
{
this.connection = connection; Db = db; Student = student; OtherStudent = otherStudent;
Term = term; Batch = batch; DeclarationDimension = declarationDimension;
CounselorScope = new TestScope(counselorId, null, DataScope.Class, SystemRoles.Counselor);
StudentScope = new TestScope(student.UserId!.Value, null, DataScope.Self, SystemRoles.Student);
}
public static async Task<Fixture> CreateAsync(bool includeSecondStudent = false, bool secondClass = false)
{
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 manager = new ApplicationUser { Id = Guid.NewGuid(), UserName = "manager", NormalizedUserName = "MANAGER", DisplayName = "管理员", SecurityStamp = Guid.NewGuid().ToString() };
var studentUser = new ApplicationUser { Id = Guid.NewGuid(), UserName = "student", NormalizedUserName = "STUDENT", DisplayName = "学生甲", SecurityStamp = Guid.NewGuid().ToString() };
var counselorId = Guid.NewGuid();
var counselor = new ApplicationUser { Id = counselorId, UserName = "counselor", NormalizedUserName = "COUNSELOR", DisplayName = "辅导员", SecurityStamp = Guid.NewGuid().ToString() };
var college = new College { Code = "CS", Name = "计算机学院" };
var major = new Major { Code = "SE", Name = "软件工程", CollegeId = college.Id, DegreeType = "工学" };
var assignedClass = new AdministrativeClass { Code = "SE2601", Name = "软件 2601", MajorId = major.Id, Grade = 2026, CounselorUserId = counselorId };
var otherCounselor = secondClass ? new ApplicationUser { Id = Guid.NewGuid(), UserName = "counselor2", NormalizedUserName = "COUNSELOR2", DisplayName = "其他辅导员", SecurityStamp = Guid.NewGuid().ToString() } : null;
var otherClass = secondClass
? new AdministrativeClass { Code = "SE2602", Name = "软件 2602", MajorId = major.Id, Grade = 2026, CounselorUserId = otherCounselor!.Id }
: assignedClass;
var student = new Student { StudentNumber = "202600001", Name = "学生甲", Gender = Gender.Male, AdministrativeClassId = assignedClass.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1), UserId = studentUser.Id };
Student? otherStudent = includeSecondStudent ? new Student { StudentNumber = "202600002", Name = "学生乙", Gender = Gender.Female, AdministrativeClassId = otherClass.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1) } : null;
var term = new AcademicTerm { Code = "2026-A", Name = "2026-2027 学年第一学期", AcademicYear = "2026-2027", Season = TermSeason.Autumn, StartDate = new DateOnly(2026, 9, 1), EndDate = new DateOnly(2027, 1, 20) };
var scheme = new ComprehensiveAssessmentScheme { Name = "测试方案", Status = ComprehensiveAssessmentSchemeStatus.Published, CreatedByUserId = manager.Id, PublishedAt = DateTime.UtcNow };
var academic = new ComprehensiveAssessmentDimension { Scheme = scheme, Code = "academic", Name = "学业表现", SourceType = ComprehensiveAssessmentSourceType.Academic, Weight = 60, MaxScore = 100, SortOrder = 1, IsRequired = true };
var declaration = new ComprehensiveAssessmentDimension { Scheme = scheme, Code = "honors", Name = "荣誉实践", SourceType = ComprehensiveAssessmentSourceType.Declaration, Weight = 40, MaxScore = 100, SortOrder = 2 };
var batch = new ComprehensiveAssessmentBatch { Scheme = scheme, Name = "2026 综合测评", AcademicYear = "2026-2027", AcademicTermId = term.Id, CollegeId = college.Id, Status = ComprehensiveAssessmentBatchStatus.Reviewing, CreatedByUserId = manager.Id };
db.AddRange(manager, studentUser, counselor, college, major, assignedClass);
if (secondClass) db.AddRange(otherCounselor!, otherClass);
db.AddRange(student, term, scheme, academic, declaration, batch);
if (otherStudent is not null) db.Add(otherStudent);
await db.SaveChangesAsync();
return new Fixture(connection, db, student, otherStudent, term, batch, declaration, counselorId);
}
public async ValueTask DisposeAsync() { await Db.DisposeAsync(); await connection.DisposeAsync(); }
}
private sealed class TestScope(Guid userId, Guid? collegeId, DataScope scope, string role) : ICurrentUserDataScope
{
public CurrentUserScope Current { get; } = new(userId, "测试用户", collegeId, scope, new HashSet<string>([role]));
}
}