236 lines
13 KiB
C#
236 lines
13 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.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 DormitoryHygieneControllerTests
|
|
{
|
|
[Fact]
|
|
public async Task UpsertScores_CalculatesGradeAndKeepsPublishedState()
|
|
{
|
|
await using var fixture = await Fixture.CreateAsync();
|
|
fixture.Batch.Status = DormitoryHygieneBatchStatus.Published;
|
|
await fixture.Db.SaveChangesAsync();
|
|
var controller = new DormitoryHygieneController(fixture.Db, fixture.AllScope);
|
|
|
|
var result = await controller.UpsertScores(fixture.Batch.Id,
|
|
new UpsertDormitoryHygieneScoresRequest([
|
|
new DormitoryHygieneScoreRequest(fixture.Room.Id, 18, 17, 16, 19, 20, "物品摆放需改进", "已复核")
|
|
]), CancellationToken.None);
|
|
|
|
Assert.IsType<OkObjectResult>(result);
|
|
fixture.Db.ChangeTracker.Clear();
|
|
var score = await fixture.Db.DormitoryHygieneScores.SingleAsync();
|
|
Assert.Equal(90, score.TotalScore);
|
|
Assert.Equal(DormitoryHygieneGrade.Excellent, score.Grade);
|
|
Assert.Equal("物品摆放需改进", score.Issues);
|
|
Assert.Equal(DormitoryHygieneBatchStatus.Published,
|
|
(await fixture.Db.DormitoryHygieneBatches.SingleAsync()).Status);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task CollegeViewer_OnlySeesRoomsOccupiedByAccessibleStudents()
|
|
{
|
|
await using var fixture = await Fixture.CreateAsync(includeSecondCollege: true);
|
|
var controller = new DormitoryHygieneController(fixture.Db, fixture.CollegeScope);
|
|
|
|
var result = Assert.IsType<OkObjectResult>(await controller.GetRooms(pageSize: 30, ct: CancellationToken.None));
|
|
var json = JsonSerializer.Serialize(result.Value);
|
|
|
|
Assert.Contains(fixture.Room.RoomNumber, json);
|
|
Assert.DoesNotContain(fixture.OtherRoom!.RoomNumber, json);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Mine_ReturnsOnlyPublishedScoresForCurrentDormitory()
|
|
{
|
|
await using var fixture = await Fixture.CreateAsync();
|
|
var published = fixture.Batch;
|
|
published.Status = DormitoryHygieneBatchStatus.Published;
|
|
var draft = new DormitoryHygieneBatch { Name = "未发布检查", InspectionDate = new DateOnly(2026, 10, 19) };
|
|
fixture.Db.DormitoryHygieneScores.AddRange(
|
|
ScoreFor(published.Id, fixture.Room.Id, 95),
|
|
ScoreFor(draft.Id, fixture.Room.Id, 60));
|
|
fixture.Db.Add(draft);
|
|
await fixture.Db.SaveChangesAsync();
|
|
var controller = new DormitoryHygieneController(fixture.Db, fixture.StudentScope);
|
|
|
|
var result = Assert.IsType<OkObjectResult>(await controller.Mine(CancellationToken.None));
|
|
var json = JsonSerializer.Serialize(result.Value);
|
|
|
|
Assert.Contains(published.Id.ToString(), json);
|
|
Assert.DoesNotContain(draft.Id.ToString(), json);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Mine_MatchesScoresToActualStayWindowsAcrossTransfer()
|
|
{
|
|
await using var fixture = await Fixture.CreateAsync();
|
|
var targetRoom = new DormitoryRoom { DormitoryBuildingId = fixture.Room.DormitoryBuildingId, RoomNumber = "102", Floor = 1 };
|
|
var targetBed = new DormitoryBed { DormitoryRoomId = targetRoom.Id, BedNumber = "1" };
|
|
var occupancy = await fixture.Db.DormitoryOccupancies.SingleAsync(x => x.StudentId == fixture.Student.Id);
|
|
var originalBedId = occupancy.DormitoryBedId;
|
|
occupancy.DormitoryBedId = targetBed.Id;
|
|
occupancy.CheckInDate = new DateOnly(2026, 10, 10);
|
|
fixture.Db.AddRange(targetRoom, targetBed,
|
|
new DormitoryStayHistory { StudentId = fixture.Student.Id, ToBedId = originalBedId, Action = DormitoryStayAction.CheckIn,
|
|
EffectiveDate = new DateOnly(2026, 9, 1), OperatedByUserId = fixture.AllScope.Current.UserId },
|
|
new DormitoryStayHistory { StudentId = fixture.Student.Id, FromBedId = originalBedId, ToBedId = targetBed.Id,
|
|
Action = DormitoryStayAction.Transfer, EffectiveDate = new DateOnly(2026, 10, 10), OperatedByUserId = fixture.AllScope.Current.UserId });
|
|
var batches = new[]
|
|
{
|
|
new DormitoryHygieneBatch { Name = "原宿舍入住期间", InspectionDate = new DateOnly(2026, 9, 15), Status = DormitoryHygieneBatchStatus.Published },
|
|
new DormitoryHygieneBatch { Name = "原宿舍迁出之后", InspectionDate = new DateOnly(2026, 10, 15), Status = DormitoryHygieneBatchStatus.Published },
|
|
new DormitoryHygieneBatch { Name = "新宿舍入住之前", InspectionDate = new DateOnly(2026, 9, 20), Status = DormitoryHygieneBatchStatus.Published },
|
|
new DormitoryHygieneBatch { Name = "新宿舍入住之后", InspectionDate = new DateOnly(2026, 10, 16), Status = DormitoryHygieneBatchStatus.Published }
|
|
};
|
|
fixture.Db.AddRange(batches);
|
|
fixture.Db.AddRange(ScoreFor(batches[0].Id, fixture.Room.Id, 90), ScoreFor(batches[1].Id, fixture.Room.Id, 80),
|
|
ScoreFor(batches[2].Id, targetRoom.Id, 70), ScoreFor(batches[3].Id, targetRoom.Id, 95));
|
|
await fixture.Db.SaveChangesAsync();
|
|
|
|
var result = Assert.IsType<OkObjectResult>(await new DormitoryHygieneController(fixture.Db, fixture.StudentScope).Mine(CancellationToken.None));
|
|
var json = JsonSerializer.Serialize(result.Value);
|
|
|
|
Assert.Contains(batches[0].Id.ToString(), json);
|
|
Assert.Contains(batches[3].Id.ToString(), json);
|
|
Assert.DoesNotContain(batches[1].Id.ToString(), json);
|
|
Assert.DoesNotContain(batches[2].Id.ToString(), json);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Publish_RejectsBatchWithoutScores()
|
|
{
|
|
await using var fixture = await Fixture.CreateAsync();
|
|
var controller = new DormitoryHygieneController(fixture.Db, fixture.AllScope);
|
|
|
|
var result = await controller.Publish(fixture.Batch.Id, CancellationToken.None);
|
|
|
|
var conflict = Assert.IsType<ConflictObjectResult>(result);
|
|
Assert.Contains("没有宿舍成绩", Assert.IsType<ProblemDetails>(conflict.Value).Detail);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Export_ReturnsCurrentBatchScoresWorkbook()
|
|
{
|
|
await using var fixture = await Fixture.CreateAsync();
|
|
fixture.Db.Add(ScoreFor(fixture.Batch.Id, fixture.Room.Id, 90));
|
|
await fixture.Db.SaveChangesAsync();
|
|
var controller = new DormitoryHygieneController(fixture.Db, fixture.AllScope);
|
|
|
|
var result = Assert.IsType<FileContentResult>(await controller.Export(fixture.Batch.Id, CancellationToken.None));
|
|
|
|
using var workbook = new XLWorkbook(new MemoryStream(result.FileContents));
|
|
var sheet = workbook.Worksheet("宿舍卫生成绩");
|
|
Assert.Equal("宿舍楼", sheet.Cell("A1").GetString());
|
|
Assert.Equal("楼层", sheet.Cell("C1").GetString());
|
|
Assert.Equal("总分", sheet.Cell("K1").GetString());
|
|
Assert.Equal(90, sheet.Cell("K2").GetDouble());
|
|
Assert.Equal("优秀", sheet.Cell("L2").GetString());
|
|
}
|
|
|
|
private static DormitoryHygieneScore ScoreFor(Guid batchId, Guid roomId, decimal total) => new()
|
|
{
|
|
DormitoryHygieneBatchId = batchId,
|
|
DormitoryRoomId = roomId,
|
|
FloorScore = total / 5,
|
|
BeddingScore = total / 5,
|
|
BelongingsScore = total / 5,
|
|
FacilitiesScore = total / 5,
|
|
SafetyScore = total / 5,
|
|
TotalScore = total,
|
|
Grade = total >= 90 ? DormitoryHygieneGrade.Excellent : DormitoryHygieneGrade.Qualified
|
|
};
|
|
|
|
private sealed class Fixture : IAsyncDisposable
|
|
{
|
|
private readonly SqliteConnection connection;
|
|
public AppDbContext Db { get; }
|
|
public DormitoryRoom Room { get; }
|
|
public Student Student { get; }
|
|
public DormitoryRoom? OtherRoom { get; }
|
|
public DormitoryHygieneBatch Batch { get; }
|
|
public ICurrentUserDataScope AllScope { get; }
|
|
public ICurrentUserDataScope CollegeScope { get; }
|
|
public ICurrentUserDataScope StudentScope { get; }
|
|
|
|
private Fixture(SqliteConnection connection, AppDbContext db, DormitoryRoom room, Student student,
|
|
DormitoryRoom? otherRoom, DormitoryHygieneBatch batch, Guid collegeId, Guid userId)
|
|
{
|
|
this.connection = connection;
|
|
Db = db;
|
|
Room = room;
|
|
Student = student;
|
|
OtherRoom = otherRoom;
|
|
Batch = batch;
|
|
AllScope = new TestScope(Guid.NewGuid(), null, DataScope.All, SystemRoles.DormitoryAdmin);
|
|
CollegeScope = new TestScope(Guid.NewGuid(), collegeId, DataScope.College, SystemRoles.CollegeAdmin);
|
|
StudentScope = new TestScope(userId, collegeId, DataScope.Self, SystemRoles.Student);
|
|
}
|
|
|
|
public static async Task<Fixture> CreateAsync(bool includeSecondCollege = 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 userId = Guid.NewGuid();
|
|
var user = new ApplicationUser { Id = userId, UserName = "student", DisplayName = "学生甲" };
|
|
var college = new College { Code = "CS", Name = "计算机学院" };
|
|
var major = new Major { Code = "SE", Name = "软件工程", CollegeId = college.Id, DegreeType = "工学" };
|
|
var classRoom = new AdministrativeClass { Code = "SE2026", Name = "软件 2026 级", MajorId = major.Id, Grade = 2026 };
|
|
var student = new Student { StudentNumber = "202600001", Name = "学生甲", UserId = userId, AdministrativeClassId = classRoom.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1) };
|
|
var building = new DormitoryBuilding { Code = "MY1", Name = "梅园 1 栋", FloorCount = 9 };
|
|
var room = new DormitoryRoom { DormitoryBuildingId = building.Id, RoomNumber = "101", Floor = 1 };
|
|
var beds = Enumerable.Range(1, 4).Select(number => new DormitoryBed
|
|
{
|
|
DormitoryRoomId = room.Id,
|
|
BedNumber = number.ToString()
|
|
}).ToArray();
|
|
var occupancy = new DormitoryOccupancy { DormitoryBedId = beds[0].Id, StudentId = student.Id, CheckInDate = new DateOnly(2026, 9, 1) };
|
|
var batch = new DormitoryHygieneBatch { Name = "第七周检查", InspectionDate = new DateOnly(2026, 10, 16) };
|
|
db.AddRange(user, college, major, classRoom, student, building, room, occupancy, batch);
|
|
db.AddRange(beds);
|
|
DormitoryRoom? otherRoom = null;
|
|
if (includeSecondCollege)
|
|
{
|
|
var otherCollege = new College { Code = "ART", Name = "艺术学院" };
|
|
var otherMajor = new Major { Code = "ART", Name = "艺术学", CollegeId = otherCollege.Id, DegreeType = "艺术学" };
|
|
var otherClass = new AdministrativeClass { Code = "ART2026", Name = "艺术 2026 级", MajorId = otherMajor.Id, Grade = 2026 };
|
|
var otherStudent = new Student { StudentNumber = "202600002", Name = "学生乙", AdministrativeClassId = otherClass.Id, EnrollmentYear = 2026, EnrollmentDate = new DateOnly(2026, 9, 1) };
|
|
var otherBuilding = new DormitoryBuilding { Code = "LY2", Name = "兰园 2 栋", FloorCount = 9 };
|
|
otherRoom = new DormitoryRoom { DormitoryBuildingId = otherBuilding.Id, RoomNumber = "902", Floor = 9 };
|
|
var otherBeds = Enumerable.Range(1, 4).Select(number => new DormitoryBed
|
|
{
|
|
DormitoryRoomId = otherRoom.Id,
|
|
BedNumber = number.ToString()
|
|
}).ToArray();
|
|
db.AddRange(otherCollege, otherMajor, otherClass, otherStudent, otherBuilding, otherRoom,
|
|
new DormitoryOccupancy { DormitoryBedId = otherBeds[0].Id, StudentId = otherStudent.Id, CheckInDate = new DateOnly(2026, 9, 1) });
|
|
db.AddRange(otherBeds);
|
|
}
|
|
await db.SaveChangesAsync();
|
|
return new Fixture(connection, db, room, student, otherRoom, batch, college.Id, userId);
|
|
}
|
|
|
|
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]));
|
|
}
|
|
}
|