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

639 lines
38 KiB
C#

using ClosedXML.Excel;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Contracts;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
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;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging.Abstractions;
namespace Jiaowu.Api.Tests;
public sealed class ComprehensiveAssessmentsControllerTests
{
[Fact]
public async Task Manual_recalculation_resets_previous_attempts()
{
await using var fixture = await Fixture.CreateAsync();
fixture.Batch.CalculationStatus = ComprehensiveAssessmentCalculationStatus.Failed;
var outbox = BackgroundJobOutboxMessage.Create(BackgroundJobKind.ComprehensiveAssessmentCalculation, fixture.Batch.Id);
outbox.State = BackgroundJobOutboxState.Completed;
outbox.ProcessingAttempts = 29110;
outbox.LastError = "旧错误";
fixture.Db.BackgroundJobOutboxMessages.Add(outbox);
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
Assert.IsType<AcceptedResult>(await controller.QueueCalculation(fixture.Batch.Id, CancellationToken.None));
Assert.Equal(0, outbox.ProcessingAttempts);
Assert.Null(outbox.LastError);
Assert.Equal(BackgroundJobOutboxState.Pending, outbox.State);
}
[Fact]
public async Task Declaration_accepts_attachment_as_evidence_and_obeys_reader_scope()
{
await using var fixture = await Fixture.CreateAsync();
fixture.Batch.Status = ComprehensiveAssessmentBatchStatus.Collecting;
var rule = new ComprehensiveAssessmentRule { ComprehensiveAssessmentSchemeId = fixture.Batch.ComprehensiveAssessmentSchemeId,
ComprehensiveAssessmentDimensionId = fixture.DeclarationDimension.Id, Category = "竞赛", Level = "省级", Score = 5 };
fixture.Db.ComprehensiveAssessmentRules.Add(rule);
await fixture.Db.SaveChangesAsync();
var directory = Path.Combine(Path.GetTempPath(), "jiaowu-assessment-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?> { ["Attachments:LocalPath"] = directory }).Build();
var environment = new AttachmentTestEnvironment { ContentRootPath = directory };
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.StudentScope);
var request = new AssessmentDeclarationWithAttachments { BatchId = fixture.Batch.Id, RuleId = rule.Id, Title = "获奖",
OccurredOn = new DateOnly(2026, 10, 1), Files = [new FormFile(new MemoryStream([1, 2]), 0, 2, "files", "proof.pdf")] };
Assert.IsType<CreatedResult>(await controller.CreateDeclarationWithAttachments(request, config, environment, NullLogger<ComprehensiveAssessmentsController>.Instance, CancellationToken.None));
var declaration = await fixture.Db.ComprehensiveAssessmentDeclarations.SingleAsync();
Assert.Single(await fixture.Db.ApprovalAttachments.ToListAsync());
var reader = new ApprovalAttachmentsController(fixture.Db, fixture.StudentScope, config, environment);
var outsider = new ApprovalAttachmentsController(fixture.Db, new TestScope(Guid.NewGuid(), null, DataScope.Self, SystemRoles.Student), config, environment);
Assert.IsType<OkObjectResult>(await reader.List("AssessmentDeclaration", declaration.Id, CancellationToken.None));
Assert.IsType<NotFoundResult>(await outsider.List("AssessmentDeclaration", declaration.Id, CancellationToken.None));
Assert.IsType<NoContentResult>(await controller.SubmitDeclaration(declaration.Id, CancellationToken.None));
Assert.IsType<ConflictObjectResult>(await controller.UpdateDeclarationWithAttachments(declaration.Id, request, config, environment, NullLogger<ComprehensiveAssessmentsController>.Instance, CancellationToken.None));
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task Declaration_edit_does_not_overwrite_concurrent_submission()
{
await using var fixture = await Fixture.CreateAsync();
var draft = Declaration(fixture.Batch.Id, fixture.Student.Id, fixture.DeclarationDimension.Id, "草稿");
draft.Status = ComprehensiveAssessmentDeclarationStatus.Draft;
fixture.Db.ComprehensiveAssessmentDeclarations.Add(draft);
await fixture.Db.SaveChangesAsync();
var options = new DbContextOptionsBuilder<AppDbContext>().UseSqlite(fixture.Db.Database.GetDbConnection()).Options;
await using var submitDb = new AppDbContext(options);
await using var editDb = new AppDbContext(options);
var submitted = await submitDb.ComprehensiveAssessmentDeclarations.SingleAsync(x => x.Id == draft.Id);
var edited = await editDb.ComprehensiveAssessmentDeclarations.SingleAsync(x => x.Id == draft.Id);
submitted.Status = ComprehensiveAssessmentDeclarationStatus.Submitted;
await submitDb.SaveChangesAsync();
edited.Title = "修改后的材料";
edited.UpdatedAt = DateTime.UtcNow;
await Assert.ThrowsAsync<DbUpdateConcurrencyException>(() => editDb.SaveChangesAsync());
}
private sealed class AttachmentTestEnvironment : IWebHostEnvironment
{
public string ApplicationName { get; set; } = "Jiaowu.Api.Tests";
public IFileProvider WebRootFileProvider { get; set; } = new NullFileProvider();
public string WebRootPath { get; set; } = "";
public string EnvironmentName { get; set; } = "Development";
public string ContentRootPath { get; set; } = "";
public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
}
[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 LiveCalculation_AndDimensionLock_PreserveFrozenScoreForFinalResult()
{
await using var fixture = await Fixture.CreateAsync();
var academicStatistic = new StudentAcademicTermStatistic
{
StudentId = fixture.Student.Id,
AcademicTermId = fixture.Term.Id,
CourseCount = 6,
WeightedAverageScore = 80,
AverageScore = 79,
CalculatedAt = DateTime.UtcNow
};
fixture.Db.StudentAcademicTermStatistics.Add(academicStatistic);
fixture.Batch.PlanPublishedAt = DateTime.UtcNow;
fixture.Batch.LiveEstimationEnabled = true;
fixture.Batch.PendingCalculationMode = ComprehensiveAssessmentCalculationMode.Live;
fixture.Batch.LiveCalculationStatus = ComprehensiveAssessmentCalculationStatus.Queued;
await fixture.Db.SaveChangesAsync();
var processor = new ComprehensiveAssessmentCalculationProcessor(fixture.Db);
await processor.ProcessAsync(fixture.Batch.Id, CancellationToken.None);
var live = await fixture.Db.ComprehensiveAssessmentLiveResults.Include(x => x.Details)
.SingleAsync(x => x.StudentId == fixture.Student.Id);
Assert.Equal(48m, live.EstimatedTotalScore);
Assert.Empty(await fixture.Db.ComprehensiveAssessmentResults.ToListAsync());
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
var lockResponse = await controller.LockDimension(
fixture.Batch.Id, fixture.AcademicDimension.Id,
new LockAssessmentDimensionRequest(), CancellationToken.None);
Assert.IsType<OkObjectResult>(lockResponse);
lockResponse = await controller.LockDimension(
fixture.Batch.Id, fixture.DeclarationDimension.Id,
new LockAssessmentDimensionRequest(), CancellationToken.None);
Assert.IsType<OkObjectResult>(lockResponse);
academicStatistic.WeightedAverageScore = 20;
fixture.Batch.PendingCalculationMode = ComprehensiveAssessmentCalculationMode.Final;
fixture.Batch.CalculationStatus = ComprehensiveAssessmentCalculationStatus.Queued;
await fixture.Db.SaveChangesAsync();
await processor.ProcessAsync(fixture.Batch.Id, CancellationToken.None);
fixture.Db.ChangeTracker.Clear();
var finalResult = await fixture.Db.ComprehensiveAssessmentResults.Include(x => x.Details)
.SingleAsync(x => x.StudentId == fixture.Student.Id);
var academicDetail = finalResult.Details.Single(x =>
x.ComprehensiveAssessmentDimensionId == fixture.AcademicDimension.Id);
Assert.Equal(80m, academicDetail.RawScore);
Assert.Equal(48m, finalResult.TotalScore);
var dimensionLocks = await fixture.Db.ComprehensiveAssessmentDimensionLocks.ToListAsync();
Assert.Equal(2, dimensionLocks.Count);
Assert.All(dimensionLocks, dimensionLock =>
{
Assert.Equal(ComprehensiveAssessmentDimensionLockStatus.Locked, dimensionLock.Status);
Assert.Equal(1, dimensionLock.Version);
});
}
[Fact]
public async Task LiveAndFinalCalculations_WorkWithRetryingExecutionStrategy()
{
await using var fixture = await Fixture.CreateAsync(useRetryingExecutionStrategy: true);
fixture.Batch.PlanPublishedAt = DateTime.UtcNow;
fixture.Batch.LiveEstimationEnabled = true;
fixture.Batch.PendingCalculationMode = ComprehensiveAssessmentCalculationMode.Live;
fixture.Batch.LiveCalculationStatus = ComprehensiveAssessmentCalculationStatus.Queued;
await fixture.Db.SaveChangesAsync();
Assert.True(fixture.Db.Database.CreateExecutionStrategy().RetriesOnFailure);
await new ComprehensiveAssessmentCalculationProcessor(fixture.Db)
.ProcessAsync(fixture.Batch.Id, CancellationToken.None);
Assert.Equal(ComprehensiveAssessmentCalculationStatus.Succeeded,
(await fixture.Db.ComprehensiveAssessmentBatches.FindAsync(fixture.Batch.Id))!
.LiveCalculationStatus);
Assert.Single(await fixture.Db.ComprehensiveAssessmentLiveResults.ToListAsync());
fixture.Batch.PlanPublishedAt = null;
fixture.Batch.PendingCalculationMode = ComprehensiveAssessmentCalculationMode.Final;
fixture.Batch.CalculationStatus = ComprehensiveAssessmentCalculationStatus.Queued;
await fixture.Db.SaveChangesAsync();
await new ComprehensiveAssessmentCalculationProcessor(fixture.Db)
.ProcessAsync(fixture.Batch.Id, CancellationToken.None);
Assert.Equal(ComprehensiveAssessmentCalculationStatus.Succeeded,
(await fixture.Db.ComprehensiveAssessmentBatches.FindAsync(fixture.Batch.Id))!
.CalculationStatus);
Assert.Single(await fixture.Db.ComprehensiveAssessmentResults.ToListAsync());
}
[Fact]
public async Task Reviewed_declaration_cannot_be_deleted_after_it_returns_to_draft()
{
await using var fixture = await Fixture.CreateAsync();
fixture.Batch.Status = ComprehensiveAssessmentBatchStatus.Collecting;
var item = Declaration(fixture.Batch.Id, fixture.Student.Id, fixture.DeclarationDimension.Id, "已审核材料");
item.Status = ComprehensiveAssessmentDeclarationStatus.Draft;
fixture.Db.ComprehensiveAssessmentDeclarations.Add(item);
fixture.Db.ApprovalReviewEvents.Add(new ApprovalReviewEvent { Type = "AssessmentDeclaration", ApprovalId = item.Id, ReviewerUserId = fixture.CounselorScope.Current.UserId, ReviewedAt = DateTime.UtcNow, Approved = false });
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.StudentScope);
Assert.IsType<ConflictObjectResult>(await controller.DeleteDeclaration(item.Id, CancellationToken.None));
Assert.True(await fixture.Db.ComprehensiveAssessmentDeclarations.AnyAsync(x => x.Id == item.Id));
}
[Fact]
public async Task CounselorPendingDeclarations_IsLimitedToAssignedClasses()
{
await using var fixture = await Fixture.CreateAsync(includeSecondStudent: true, secondClass: true);
var own = Declaration(fixture.Batch.Id, fixture.Student.Id, fixture.DeclarationDimension.Id, "本班材料");
var other = Declaration(fixture.Batch.Id, fixture.OtherStudent!.Id, fixture.DeclarationDimension.Id, "其他班材料");
fixture.Db.ComprehensiveAssessmentDeclarations.AddRange(own, other);
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.CounselorScope);
var response = Assert.IsType<OkObjectResult>(await controller.PendingDeclarations(token: CancellationToken.None));
var page = Assert.IsType<PagedResult<AssessmentDeclarationView>>(response.Value);
Assert.Single(page.Items);
Assert.Equal("本班材料", page.Items.Single().Title);
var targeted = Assert.IsType<OkObjectResult>(await controller.PendingDeclarations(token: CancellationToken.None, id: own.Id));
Assert.Equal(own.Id, Assert.Single(Assert.IsType<PagedResult<AssessmentDeclarationView>>(targeted.Value).Items).Id);
var outside = Assert.IsType<OkObjectResult>(await controller.PendingDeclarations(token: CancellationToken.None, id: other.Id));
Assert.Empty(Assert.IsType<PagedResult<AssessmentDeclarationView>>(outside.Value).Items);
}
[Fact]
public async Task CounselorWithCollegeRole_CanReviewAssignedInitialAndCollegeFinalStages()
{
await using var fixture = await Fixture.CreateAsync(includeSecondStudent: true, secondClass: true);
var assigned = Declaration(fixture.Batch.Id, fixture.Student.Id, fixture.DeclarationDimension.Id, "本班初审");
var other = Declaration(fixture.Batch.Id, fixture.OtherStudent!.Id, fixture.DeclarationDimension.Id, "其他班初审");
var final = Declaration(fixture.Batch.Id, fixture.OtherStudent.Id, fixture.DeclarationDimension.Id, "学院复核");
final.Status = ComprehensiveAssessmentDeclarationStatus.CounselorApproved;
fixture.Db.ComprehensiveAssessmentDeclarations.AddRange(assigned, other, final);
await fixture.Db.SaveChangesAsync();
var scope = new TestScope(fixture.CounselorScope.Current.UserId, fixture.Batch.CollegeId,
DataScope.College, SystemRoles.Counselor, SystemRoles.CollegeAdmin);
var controller = new ComprehensiveAssessmentsController(fixture.Db, scope);
var response = Assert.IsType<OkObjectResult>(await controller.PendingDeclarations(token: CancellationToken.None));
var page = Assert.IsType<PagedResult<AssessmentDeclarationView>>(response.Value);
Assert.Equal(2, page.Total);
Assert.Contains(page.Items, x => x.Id == assigned.Id);
Assert.Contains(page.Items, x => x.Id == final.Id);
Assert.DoesNotContain(page.Items, x => x.Id == other.Id);
var request = new ReviewAssessmentDeclarationRequest(true, null, null);
Assert.IsType<NotFoundResult>(await controller.ReviewDeclaration(other.Id, request, CancellationToken.None));
Assert.IsType<NoContentResult>(await controller.ReviewDeclaration(assigned.Id, request, CancellationToken.None));
Assert.Equal(ComprehensiveAssessmentDeclarationStatus.CounselorApproved, assigned.Status);
Assert.IsType<NoContentResult>(await controller.ReviewDeclaration(final.Id, request, CancellationToken.None));
Assert.Equal(ComprehensiveAssessmentDeclarationStatus.Approved, final.Status);
var events = await fixture.Db.ApprovalReviewEvents.AsNoTracking()
.Where(x => x.Type == "AssessmentDeclaration" && (x.ApprovalId == assigned.Id || x.ApprovalId == final.Id)).ToListAsync();
Assert.Equal(2, events.Count);
Assert.All(events, e => { Assert.True(e.Approved); Assert.Equal(scope.Current.UserId, e.ReviewerUserId); });
// A later edit clears the current review fields, but the decision remains visible.
assigned.CounselorReviewedByUserId = null;
assigned.CounselorReviewedAt = null;
await fixture.Db.SaveChangesAsync();
var reviewed = await new ApprovalsController(fixture.Db, scope).GetReviewed(ct: CancellationToken.None);
var reviewedItems = Assert.IsType<ApprovalReviewedResult>(Assert.IsType<OkObjectResult>(reviewed.Result).Value).Items;
Assert.Single(reviewedItems, x => x.Type == "AssessmentDeclaration" && x.Id == assigned.Id);
Assert.Single(reviewedItems, x => x.Type == "AssessmentDeclaration" && x.Id == final.Id);
}
[Theory]
[InlineData(SystemRoles.PhysicalEducationAdmin)]
[InlineData(SystemRoles.DormitoryAdmin)]
[InlineData(SystemRoles.MaintenanceAdmin)]
public async Task LiveResults_ArePagedAndLimitedToTheCounselorsAssignedClasses(string specialistRole)
{
await using var fixture = await Fixture.CreateAsync(includeSecondStudent: true, secondClass: true);
fixture.Batch.PlanPublishedAt = DateTime.UtcNow;
fixture.Batch.LiveEstimationEnabled = true;
fixture.Db.ComprehensiveAssessmentLiveResults.AddRange(
new ComprehensiveAssessmentLiveResult
{
ComprehensiveAssessmentBatchId = fixture.Batch.Id,
StudentId = fixture.Student.Id,
EstimatedTotalScore = 82,
CalculatedAt = DateTime.UtcNow
},
new ComprehensiveAssessmentLiveResult
{
ComprehensiveAssessmentBatchId = fixture.Batch.Id,
StudentId = fixture.OtherStudent!.Id,
EstimatedTotalScore = 91,
CalculatedAt = DateTime.UtcNow
});
await fixture.Db.SaveChangesAsync();
var counselorController = new ComprehensiveAssessmentsController(
fixture.Db, new TestScope(fixture.CounselorScope.Current.UserId, null,
EffectiveDataScopeResolver.Resolve([SystemRoles.Counselor, specialistRole]),
SystemRoles.Counselor, specialistRole));
var counselorResponse = Assert.IsType<OkObjectResult>(await counselorController.GetLiveResults(
fixture.Batch.Id, token: CancellationToken.None));
var counselorPage = Assert.IsType<PagedResult<ComprehensiveAssessmentLiveResultView>>(
counselorResponse.Value);
Assert.Single(counselorPage.Items);
Assert.Equal(fixture.Student.Id, counselorPage.Items.Single().StudentId);
var collegeController = new ComprehensiveAssessmentsController(
fixture.Db, fixture.ManagerScope);
var collegeResponse = Assert.IsType<OkObjectResult>(await collegeController.GetLiveResults(
fixture.Batch.Id, token: CancellationToken.None));
var collegePage = Assert.IsType<PagedResult<ComprehensiveAssessmentLiveResultView>>(
collegeResponse.Value);
Assert.Equal(2, collegePage.Total);
var affairsRoles = new[] { SystemRoles.StudentAffairsAdmin, SystemRoles.Counselor };
var affairsController = new ComprehensiveAssessmentsController(fixture.Db,
new TestScope(Guid.NewGuid(), null, EffectiveDataScopeResolver.Resolve(affairsRoles), affairsRoles));
var affairsResponse = Assert.IsType<OkObjectResult>(await affairsController.GetLiveResults(
fixture.Batch.Id, token: CancellationToken.None));
Assert.Equal(2, Assert.IsType<PagedResult<ComprehensiveAssessmentLiveResultView>>(affairsResponse.Value).Total);
var filteredResponse = Assert.IsType<OkObjectResult>(await collegeController.GetLiveResults(
fixture.Batch.Id, classId: fixture.Student.AdministrativeClassId,
token: CancellationToken.None));
var filteredPage = Assert.IsType<PagedResult<ComprehensiveAssessmentLiveResultView>>(
filteredResponse.Value);
Assert.Single(filteredPage.Items);
Assert.Equal(fixture.Student.Id, filteredPage.Items.Single().StudentId);
var export = Assert.IsType<FileContentResult>(await collegeController.ExportLiveResults(
fixture.Batch.Id, classId: fixture.Student.AdministrativeClassId,
token: CancellationToken.None));
using var workbook = new XLWorkbook(new MemoryStream(export.FileContents));
Assert.Equal(2, workbook.Worksheet("综合测评实时预估").LastRowUsed()!.RowNumber());
var columns = Assert.IsType<OkObjectResult>(await collegeController.ExportLiveResults(
fixture.Batch.Id, classId: fixture.Student.AdministrativeClassId,
token: CancellationToken.None, columnsOnly: true));
var headers = Assert.IsType<List<string>>(columns.Value);
Assert.Contains("当前预估分", headers);
var custom = Assert.IsType<FileContentResult>(await collegeController.ExportLiveResults(
fixture.Batch.Id, classId: fixture.Student.AdministrativeClassId,
token: CancellationToken.None, columns: "1,0", format: "xlsx"));
using var selected = new XLWorkbook(new MemoryStream(custom.FileContents));
Assert.Equal("姓名", selected.Worksheet(1).Cell(1, 1).GetString());
Assert.Equal("学号", selected.Worksheet(1).Cell(1, 2).GetString());
}
[Fact]
public async Task CollegeReviewer_CannotBypassCounselorStage()
{
await using var fixture = await Fixture.CreateAsync();
var declaration = Declaration(fixture.Batch.Id, fixture.Student.Id, fixture.DeclarationDimension.Id, "待初审材料");
fixture.Db.ComprehensiveAssessmentDeclarations.Add(declaration);
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
var pendingResponse = Assert.IsType<OkObjectResult>(await controller.PendingDeclarations(token: CancellationToken.None));
var page = Assert.IsType<PagedResult<AssessmentDeclarationView>>(pendingResponse.Value);
Assert.Empty(page.Items);
var reviewResponse = await controller.ReviewDeclaration(declaration.Id,
new ReviewAssessmentDeclarationRequest(true, 5, "学院复核"), CancellationToken.None);
Assert.IsType<NotFoundResult>(reviewResponse);
}
[Fact]
public async Task DraftScheme_CanReplaceDimensionsAndRules()
{
await using var fixture = await Fixture.CreateAsync();
var scheme = fixture.Batch.Scheme!;
scheme.Status = ComprehensiveAssessmentSchemeStatus.Draft;
scheme.CollegeId = fixture.Batch.CollegeId;
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
var request = new ComprehensiveAssessmentSchemeRequest(
"本科生综合测评方案", 2, fixture.Batch.CollegeId,
ComprehensiveAssessmentRankingScope.AdministrativeClass, 7, null,
[
new ComprehensiveAssessmentDimensionRequest("academic", "学业表现", ComprehensiveAssessmentSourceType.Academic, 70, 100, 1, true, null),
new ComprehensiveAssessmentDimensionRequest("deyu", "德育", ComprehensiveAssessmentSourceType.Declaration, 30, 100, 2, false, null)
],
[new ComprehensiveAssessmentRuleRequest("deyu", "志愿服务", "校级", 5, 20, 1)]);
var response = await controller.UpdateScheme(scheme.Id, request, CancellationToken.None);
Assert.IsType<NoContentResult>(response);
fixture.Db.ChangeTracker.Clear();
var saved = await fixture.Db.ComprehensiveAssessmentSchemes.AsNoTracking()
.Include(x => x.Dimensions).Include(x => x.Rules).SingleAsync(x => x.Id == scheme.Id);
Assert.Equal(2, saved.Version);
Assert.Equal(2, saved.Dimensions.Count);
Assert.Single(saved.Rules);
}
[Fact]
public async Task DraftScheme_CanBeDeletedUnlessReferencedByBatch()
{
await using var fixture = await Fixture.CreateAsync();
var deletable = new ComprehensiveAssessmentScheme
{
Name = "待删除草稿", CollegeId = fixture.Batch.CollegeId,
CreatedByUserId = fixture.ManagerScope.Current.UserId
};
var dimension = new ComprehensiveAssessmentDimension
{
Scheme = deletable, Code = "deyu", Name = "德育",
SourceType = ComprehensiveAssessmentSourceType.Declaration,
Weight = 100, MaxScore = 100, SortOrder = 1
};
deletable.Dimensions.Add(dimension);
deletable.Rules.Add(new ComprehensiveAssessmentRule
{
Scheme = deletable, Dimension = dimension,
Category = "志愿服务", Level = "校级", Score = 5, SortOrder = 1
});
fixture.Db.ComprehensiveAssessmentSchemes.Add(deletable);
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
Assert.IsType<NoContentResult>(await controller.DeleteScheme(deletable.Id, CancellationToken.None));
Assert.False(await fixture.Db.ComprehensiveAssessmentSchemes.AnyAsync(x => x.Id == deletable.Id));
Assert.False(await fixture.Db.ComprehensiveAssessmentDimensions.AnyAsync(x => x.ComprehensiveAssessmentSchemeId == deletable.Id));
fixture.Batch.Scheme!.Status = ComprehensiveAssessmentSchemeStatus.Draft;
fixture.Batch.Scheme.CollegeId = fixture.Batch.CollegeId;
await fixture.Db.SaveChangesAsync();
var referencedResponse = await controller.DeleteScheme(fixture.Batch.Scheme.Id, CancellationToken.None);
Assert.IsType<ConflictObjectResult>(referencedResponse);
}
[Fact]
public async Task ApprovedAppeal_RequiresRecalculationBeforePublication()
{
await using var fixture = await Fixture.CreateAsync();
fixture.Batch.Status = ComprehensiveAssessmentBatchStatus.Publicizing;
fixture.Batch.CalculationStatus = ComprehensiveAssessmentCalculationStatus.Succeeded;
fixture.Batch.PublicityStartsAt = DateTime.UtcNow.AddDays(-1);
fixture.Batch.PublicityEndsAt = DateTime.UtcNow.AddDays(1);
var appeal = new ComprehensiveAssessmentAppeal
{
ComprehensiveAssessmentBatchId = fixture.Batch.Id,
StudentId = fixture.Student.Id,
Reason = "原始数据有误"
};
fixture.Db.ComprehensiveAssessmentAppeals.Add(appeal);
await fixture.Db.SaveChangesAsync();
var controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
var reviewResponse = await controller.ReviewAppeal(appeal.Id,
new ReviewAssessmentAppealRequest(true, "核验属实"), CancellationToken.None);
Assert.IsType<NoContentResult>(reviewResponse);
fixture.Db.ChangeTracker.Clear();
var batch = (await fixture.Db.ComprehensiveAssessmentBatches.FindAsync(fixture.Batch.Id))!;
Assert.Equal(ComprehensiveAssessmentCalculationStatus.NotStarted, batch.CalculationStatus);
var decision = await fixture.Db.ApprovalReviewEvents.AsNoTracking().SingleAsync(x => x.Type == "AssessmentAppeal" && x.ApprovalId == appeal.Id);
Assert.True(decision.Approved);
Assert.Equal("核验属实", decision.Comment);
controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
var publishResponse = await controller.Publish(fixture.Batch.Id,
new PublicationRequest("正式发布", true), CancellationToken.None);
Assert.IsType<ConflictObjectResult>(publishResponse);
batch.CalculationStatus = ComprehensiveAssessmentCalculationStatus.Succeeded;
batch.CalculatedAt = DateTime.UtcNow;
await fixture.Db.SaveChangesAsync();
fixture.Db.ChangeTracker.Clear();
controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
publishResponse = await controller.Publish(fixture.Batch.Id,
new PublicationRequest("仍是原公示轮次", true), CancellationToken.None);
Assert.IsType<ConflictObjectResult>(publishResponse);
fixture.Db.ChangeTracker.Clear();
controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
Assert.IsType<NoContentResult>(await controller.Publicize(fixture.Batch.Id,
new PublicationRequest("申诉修订结果"), CancellationToken.None));
fixture.Db.ChangeTracker.Clear();
controller = new ComprehensiveAssessmentsController(fixture.Db, fixture.ManagerScope);
Assert.IsType<NoContentResult>(await controller.Publish(fixture.Batch.Id,
new PublicationRequest("修订结果正式发布", true), CancellationToken.None));
}
[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 AcademicDimension { get; }
public ComprehensiveAssessmentDimension DeclarationDimension { get; }
public ICurrentUserDataScope CounselorScope { get; }
public ICurrentUserDataScope StudentScope { get; }
public ICurrentUserDataScope ManagerScope { get; }
private Fixture(SqliteConnection connection, AppDbContext db, Student student,
Student? otherStudent, AcademicTerm term, ComprehensiveAssessmentBatch batch,
ComprehensiveAssessmentDimension academicDimension,
ComprehensiveAssessmentDimension declarationDimension, Guid counselorId)
{
this.connection = connection; Db = db; Student = student; OtherStudent = otherStudent;
Term = term; Batch = batch; AcademicDimension = academicDimension;
DeclarationDimension = declarationDimension;
CounselorScope = new TestScope(counselorId, null, DataScope.Class, SystemRoles.Counselor);
StudentScope = new TestScope(student.UserId!.Value, null, DataScope.Self, SystemRoles.Student);
ManagerScope = new TestScope(batch.CreatedByUserId, batch.CollegeId, DataScope.College, SystemRoles.CollegeAdmin);
}
public static async Task<Fixture> CreateAsync(
bool includeSecondStudent = false,
bool secondClass = false,
bool useRetryingExecutionStrategy = false)
{
var connection = new SqliteConnection("Data Source=:memory:");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<AppDbContext>().UseSqlite(connection);
if (useRetryingExecutionStrategy)
{
options.ReplaceService<IExecutionStrategyFactory, RetryingExecutionStrategyFactory>();
}
var db = new AppDbContext(options.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, IsRequired = false };
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, academic, declaration, counselorId);
}
public async ValueTask DisposeAsync() { await Db.DisposeAsync(); await connection.DisposeAsync(); }
}
private sealed class RetryingExecutionStrategyFactory(
ExecutionStrategyDependencies dependencies) : IExecutionStrategyFactory
{
public IExecutionStrategy Create() => new TestRetryingExecutionStrategy(dependencies);
}
private sealed class TestRetryingExecutionStrategy(
ExecutionStrategyDependencies dependencies)
: ExecutionStrategy(dependencies, 1, TimeSpan.Zero)
{
protected override bool ShouldRetryOn(Exception exception) => false;
}
private sealed class TestScope(Guid userId, Guid? collegeId, DataScope scope, params string[] roles) : ICurrentUserDataScope
{
public CurrentUserScope Current { get; } = new(userId, "测试用户", collegeId, scope, new HashSet<string>(roles));
}
}