Files
Academic-Affairs-System/tests/Jiaowu.Api.Tests/DormitoryServicesControllerTests.cs
T
2026-10-21 21:28:29 +08:00

272 lines
15 KiB
C#

using System.Text.Json;
using ClosedXML.Excel;
using Jiaowu.Api.Controllers;
using Jiaowu.Api.Domain.Academic;
using Jiaowu.Api.Domain.Identity;
using Jiaowu.Api.Domain.System;
using Jiaowu.Api.Infrastructure.Auth;
using Jiaowu.Api.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Jiaowu.Api.Tests;
public sealed class DormitoryServicesControllerTests
{
[Fact]
public async Task AutomaticPreview_PrefersRoomWithSameMajorOccupant()
{
await using var fixture = await Fixture.CreateAsync();
var controller = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
var result = await controller.BuildAutomaticAssignments(
[fixture.UnassignedStudent.Id], [], CancellationToken.None);
var json = JsonSerializer.Serialize(result);
Assert.Contains(fixture.SameMajorVacantBed.Id.ToString(), json);
Assert.Contains("\"RoomNumber\":\"101\"", json);
}
[Fact]
public async Task AutomaticPreview_QueuesDurableBackgroundJob()
{
await using var fixture = await Fixture.CreateAsync();
var controller = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
var result = Assert.IsType<AcceptedResult>(await controller.PreviewAllocation(
new DormitoryAllocationPreviewRequest([fixture.UnassignedStudent.Id], []), CancellationToken.None));
var batch = await fixture.Db.DormitoryAllocationBatches.SingleAsync();
var outbox = await fixture.Db.BackgroundJobOutboxMessages.SingleAsync();
Assert.Equal(DormitoryAllocationBatchStatus.Queued, batch.Status);
Assert.Equal(BackgroundJobKind.DormitoryAutomaticAllocation, outbox.JobKind);
Assert.Equal(batch.Id, outbox.JobId);
Assert.Contains(fixture.UnassignedStudent.Id.ToString(), batch.RequestPayload);
Assert.NotNull(result.Value);
var preview = await controller.BuildAutomaticAssignments(
[fixture.UnassignedStudent.Id], [], CancellationToken.None);
batch.Status = DormitoryAllocationBatchStatus.PreviewReady;
batch.ResultPayload = JsonSerializer.Serialize(preview);
await fixture.Db.SaveChangesAsync();
var status = Assert.IsType<OkObjectResult>(await controller.GetAllocationJob(
batch.Id, CancellationToken.None));
Assert.Contains(fixture.SameMajorVacantBed.Id.ToString(), JsonSerializer.Serialize(status.Value));
}
[Fact]
public async Task UnassignedStudents_UsesRequestedServerPage()
{
await using var fixture = await Fixture.CreateAsync();
for (var index = 10; index < 21; index++)
fixture.Db.Add(new Student
{
StudentNumber = $"2026000{index}", Name = $"待分配 {index}", Gender = Gender.Male,
AdministrativeClassId = fixture.UnassignedStudent.AdministrativeClassId,
EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1)
});
await fixture.Db.SaveChangesAsync();
var controller = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
var result = Assert.IsType<OkObjectResult>(await controller.GetUnassignedStudents(
page: 2, pageSize: 10, ct: CancellationToken.None));
using var json = JsonDocument.Parse(JsonSerializer.Serialize(result.Value));
Assert.Equal(12, json.RootElement.GetProperty("Total").GetInt32());
Assert.Equal(2, json.RootElement.GetProperty("Page").GetInt32());
Assert.Equal(2, json.RootElement.GetProperty("Items").GetArrayLength());
}
[Fact]
public async Task CommitAllocation_CreatesOccupancyBatchAndHistory()
{
await using var fixture = await Fixture.CreateAsync();
var controller = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
var result = await controller.CommitAllocation(new CommitDormitoryAllocationRequest(
"2026 级集中分配", DormitoryAllocationMode.Automatic, new DateOnly(2026, 9, 1), "迎新分配",
[new DormitoryAllocationItem(fixture.UnassignedStudent.Id, fixture.SameMajorVacantBed.Id)]), CancellationToken.None);
Assert.IsType<OkObjectResult>(result);
fixture.Db.ChangeTracker.Clear();
var occupancy = await fixture.Db.DormitoryOccupancies.SingleAsync(x => x.StudentId == fixture.UnassignedStudent.Id);
Assert.Equal(fixture.SameMajorVacantBed.Id, occupancy.DormitoryBedId);
Assert.Equal(new DateOnly(2026, 9, 1), occupancy.CheckInDate);
Assert.Equal(1, await fixture.Db.DormitoryAllocationBatches.CountAsync());
Assert.Equal(DormitoryStayAction.CheckIn,
(await fixture.Db.DormitoryStayHistories.SingleAsync(x => x.StudentId == fixture.UnassignedStudent.Id)).Action);
}
[Fact]
public async Task DirectTransfer_MovesStudentAndRecordsHistory()
{
await using var fixture = await Fixture.CreateAsync();
var controller = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
var result = await controller.Transfer(fixture.ResidentStudent.Id,
new DormitoryTransferRequest(fixture.TransferTargetBed.Id, new DateOnly(2026, 10, 19), "楼层调整"),
CancellationToken.None);
Assert.IsType<NoContentResult>(result);
fixture.Db.ChangeTracker.Clear();
Assert.Equal(fixture.TransferTargetBed.Id,
(await fixture.Db.DormitoryOccupancies.SingleAsync(x => x.StudentId == fixture.ResidentStudent.Id)).DormitoryBedId);
var history = await fixture.Db.DormitoryStayHistories.SingleAsync();
Assert.Equal(DormitoryStayAction.Transfer, history.Action);
Assert.Equal(fixture.ResidentBed.Id, history.FromBedId);
Assert.Equal(fixture.TransferTargetBed.Id, history.ToBedId);
}
[Fact]
public async Task CheckoutApplication_AfterTwoReviews_RemovesOccupancy()
{
await using var fixture = await Fixture.CreateAsync();
var studentController = new DormitoryServicesController(fixture.Db, fixture.StudentScope);
var create = await studentController.CreateApplication(
new CreateDormitoryApplicationRequest(DormitoryApplicationType.Checkout, null, null, "校外实习"),
CancellationToken.None);
Assert.IsType<OkObjectResult>(create);
var application = await fixture.Db.DormitoryApplications.SingleAsync();
var reviewer = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
Assert.IsType<NoContentResult>(await reviewer.CounselorReview(application.Id,
new DormitoryReviewRequest(true, "情况属实"), CancellationToken.None));
Assert.IsType<NoContentResult>(await reviewer.FinalReview(application.Id,
new DormitoryFinalReviewRequest(true, null, "准予退宿"), CancellationToken.None));
fixture.Db.ChangeTracker.Clear();
Assert.False(await fixture.Db.DormitoryOccupancies.AnyAsync(x => x.StudentId == fixture.ResidentStudent.Id));
Assert.Equal(DormitoryApplicationStatus.Approved,
(await fixture.Db.DormitoryApplications.SingleAsync()).Status);
Assert.Equal(DormitoryStayAction.Checkout, (await fixture.Db.DormitoryStayHistories.SingleAsync()).Action);
}
[Fact]
public async Task ExcelImport_MergesRoomBedAndAssignsStudent_AndExportReturnsWorkbook()
{
await using var fixture = await Fixture.CreateAsync();
var controller = new DormitoryServicesController(fixture.Db, fixture.ManagerScope);
using var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add("宿舍基础数据");
string[] headers = ["楼栋编码", "楼栋名称", "校区编码", "楼层数", "楼栋住宿性别", "楼栋状态",
"房间号", "所在楼层", "房间住宿性别", "房间状态", "床位号", "床位状态", "入住学生学号", "入住日期", "备注"];
for (var column = 0; column < headers.Length; column++) sheet.Cell(1, column + 1).Value = headers[column];
object[] values = ["MY", "梅园", "", 6, "男生", "启用", "103", 1, "男生", "启用", "1", "启用",
fixture.UnassignedStudent.StudentNumber, "2026-10-20", "批量导入"];
for (var column = 0; column < values.Length; column++) sheet.Cell(2, column + 1).Value = values[column].ToString();
await using var stream = new MemoryStream();
workbook.SaveAs(stream); stream.Position = 0;
var file = new FormFile(stream, 0, stream.Length, "file", "宿舍导入.xlsx");
Assert.IsType<OkObjectResult>(await controller.ImportExcel(file, CancellationToken.None));
fixture.Db.ChangeTracker.Clear();
var occupancy = await fixture.Db.DormitoryOccupancies.Include(x => x.DormitoryBed)!.ThenInclude(x => x!.DormitoryRoom)
.SingleAsync(x => x.StudentId == fixture.UnassignedStudent.Id);
Assert.Equal("103", occupancy.DormitoryBed!.DormitoryRoom!.RoomNumber);
Assert.Equal("1", occupancy.DormitoryBed.BedNumber);
Assert.Equal(new DateOnly(2026, 10, 20), occupancy.CheckInDate);
var export = Assert.IsType<FileContentResult>(await controller.ExportExcel(CancellationToken.None));
Assert.Equal("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", export.ContentType);
using var exported = new XLWorkbook(new MemoryStream(export.FileContents));
Assert.Equal("宿舍基础数据", exported.Worksheet(1).Name);
Assert.True(exported.Worksheet(1).RowsUsed().Count() >= 5);
}
private sealed class Fixture : IAsyncDisposable
{
private readonly SqliteConnection connection;
public AppDbContext Db { get; }
public Student ResidentStudent { get; }
public Student UnassignedStudent { get; }
public DormitoryBed ResidentBed { get; }
public DormitoryBed SameMajorVacantBed { get; }
public DormitoryBed TransferTargetBed { get; }
public ICurrentUserDataScope ManagerScope { get; }
public ICurrentUserDataScope StudentScope { get; }
private Fixture(SqliteConnection connection, AppDbContext db, ApplicationUser manager, ApplicationUser studentUser,
Student residentStudent, Student unassignedStudent, DormitoryBed residentBed,
DormitoryBed sameMajorVacantBed, DormitoryBed transferTargetBed)
{
this.connection = connection;
Db = db;
ResidentStudent = residentStudent;
UnassignedStudent = unassignedStudent;
ResidentBed = residentBed;
SameMajorVacantBed = sameMajorVacantBed;
TransferTargetBed = transferTargetBed;
ManagerScope = new TestScope(manager.Id, null, DataScope.All, SystemRoles.DormitoryAdmin);
StudentScope = new TestScope(studentUser.Id, null, DataScope.Self, SystemRoles.Student);
}
public static async Task<Fixture> 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 manager = new ApplicationUser { Id = Guid.NewGuid(), UserName = "dorm-admin", DisplayName = "宿管" };
var studentUser = new ApplicationUser { Id = Guid.NewGuid(), UserName = "resident", DisplayName = "住宿生" };
var college = new College { Code = "CS", Name = "计算机学院" };
var major = new Major { Code = "SE", Name = "软件工程", CollegeId = college.Id, DegreeType = "工学" };
var otherMajor = new Major { Code = "AI", Name = "人工智能", CollegeId = college.Id, DegreeType = "工学" };
var classRoom = new AdministrativeClass { Code = "SE2026", Name = "软件 2026 级", MajorId = major.Id, Grade = 2026 };
var otherClass = new AdministrativeClass { Code = "AI2026", Name = "人工智能 2026 级", MajorId = otherMajor.Id, Grade = 2026 };
var resident = new Student
{
StudentNumber = "202600001", Name = "住宿生", UserId = studentUser.Id, Gender = Gender.Male,
AdministrativeClassId = classRoom.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1)
};
var unassigned = new Student
{
StudentNumber = "202600002", Name = "待分配学生", Gender = Gender.Male,
AdministrativeClassId = classRoom.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1)
};
var otherStudent = new Student
{
StudentNumber = "202600003", Name = "其他专业学生", Gender = Gender.Male,
AdministrativeClassId = otherClass.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1)
};
var building = new DormitoryBuilding
{
Code = "MY", Name = "梅园", FloorCount = 6, GenderPolicy = DormitoryGenderPolicy.Male
};
var room101 = new DormitoryRoom { DormitoryBuildingId = building.Id, RoomNumber = "101", Floor = 1 };
var room102 = new DormitoryRoom { DormitoryBuildingId = building.Id, RoomNumber = "102", Floor = 1 };
var residentBed = new DormitoryBed { DormitoryRoomId = room101.Id, BedNumber = "1" };
var sameMajorVacant = new DormitoryBed { DormitoryRoomId = room101.Id, BedNumber = "2" };
var otherMajorBed = new DormitoryBed { DormitoryRoomId = room102.Id, BedNumber = "1" };
var transferTarget = new DormitoryBed { DormitoryRoomId = room102.Id, BedNumber = "2" };
db.AddRange(manager, studentUser, college);
await db.SaveChangesAsync();
db.AddRange(major, otherMajor);
await db.SaveChangesAsync();
db.AddRange(classRoom, otherClass, building);
await db.SaveChangesAsync();
db.AddRange(resident, unassigned, otherStudent, room101, room102);
await db.SaveChangesAsync();
db.AddRange(residentBed, sameMajorVacant, otherMajorBed, transferTarget);
await db.SaveChangesAsync();
db.AddRange(
new DormitoryOccupancy { StudentId = resident.Id, DormitoryBedId = residentBed.Id },
new DormitoryOccupancy { StudentId = otherStudent.Id, DormitoryBedId = otherMajorBed.Id });
await db.SaveChangesAsync();
return new Fixture(connection, db, manager, studentUser, resident, unassigned, residentBed, sameMajorVacant, transferTarget);
}
public async ValueTask DisposeAsync()
{
await Db.DisposeAsync();
await connection.DisposeAsync();
}
}
private sealed class TestScope(Guid userId, Guid? collegeId, DataScope dataScope, string role) : ICurrentUserDataScope
{
public CurrentUserScope Current { get; } = new(userId, "测试用户", collegeId, dataScope, new HashSet<string>([role]));
}
}