146 lines
5.4 KiB
C#
146 lines
5.4 KiB
C#
using System.Text.Json;
|
|
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.Excel;
|
|
using Jiaowu.Api.Infrastructure.Persistence;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Data.Sqlite;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Jiaowu.Api.Tests;
|
|
|
|
public sealed class DataQualityImportTests
|
|
{
|
|
[Fact]
|
|
public async Task Base_data_preview_reports_changes_without_writing()
|
|
{
|
|
await using var connection = new SqliteConnection("Data Source=:memory:");
|
|
await connection.OpenAsync();
|
|
await using var db = new AppDbContext(
|
|
new DbContextOptionsBuilder<AppDbContext>().UseSqlite(connection).Options);
|
|
await db.Database.EnsureCreatedAsync();
|
|
var bytes = ExcelWorkbookHelper.Create(
|
|
"数据导入",
|
|
["编码", "名称", "地址", "排序", "状态"],
|
|
[(IReadOnlyList<object?>)["MAIN", "主校区", "测试地址", 1, "启用"]]);
|
|
await using var stream = new MemoryStream(bytes);
|
|
var file = new FormFile(stream, 0, stream.Length, "file", "campuses.xlsx");
|
|
var controller = new BaseDataExcelController(db, NoOpAppCache.Instance);
|
|
|
|
var action = await controller.Import(
|
|
"campuses", file, CancellationToken.None, validateOnly: true);
|
|
|
|
var ok = Assert.IsType<OkObjectResult>(action.Result);
|
|
var result = Assert.IsType<ExcelImportResult>(ok.Value);
|
|
Assert.True(result.Preview);
|
|
Assert.Equal(1, result.Created);
|
|
Assert.Empty(await db.Campuses.AsNoTracking().ToListAsync());
|
|
}
|
|
|
|
[Fact]
|
|
public void Import_result_parser_keeps_row_level_validation_errors()
|
|
{
|
|
var details = new ValidationProblemDetails(new Dictionary<string, string[]>
|
|
{
|
|
["file"] = ["第 2 行:编码重复。", "第 3 行:学院不存在。"]
|
|
});
|
|
|
|
var errors = ImportBatchResultParser.Errors(
|
|
new BadRequestObjectResult(details));
|
|
|
|
Assert.Equal(2, errors.Count);
|
|
Assert.Contains("第 2 行:编码重复。", errors);
|
|
Assert.Contains("第 3 行:学院不存在。", errors);
|
|
}
|
|
|
|
[Fact]
|
|
public void Import_result_parser_recognizes_preview_result()
|
|
{
|
|
var expected = new ExcelImportResult(2, 3, 5, Preview: true);
|
|
|
|
var actual = ImportBatchResultParser.Success(new OkObjectResult(expected));
|
|
|
|
Assert.NotNull(actual);
|
|
Assert.True(actual.Preview);
|
|
Assert.Equal(5, actual.Total);
|
|
}
|
|
|
|
[Fact]
|
|
public void Import_result_parser_recognizes_existing_import_count_names()
|
|
{
|
|
var actual = ImportBatchResultParser.Success(
|
|
new OkObjectResult(new { imported = 7 }));
|
|
|
|
Assert.NotNull(actual);
|
|
Assert.Equal(7, actual.Updated);
|
|
Assert.Equal(7, actual.Total);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task College_admin_only_sees_import_batches_from_own_college()
|
|
{
|
|
await using var connection = new SqliteConnection("Data Source=:memory:");
|
|
await connection.OpenAsync();
|
|
await using var db = new AppDbContext(
|
|
new DbContextOptionsBuilder<AppDbContext>().UseSqlite(connection).Options);
|
|
await db.Database.EnsureCreatedAsync();
|
|
var ownCollege = new College { Code = "OWN", Name = "本学院" };
|
|
var otherCollege = new College { Code = "OTHER", Name = "其他学院" };
|
|
var ownUser = new ApplicationUser
|
|
{
|
|
UserName = "own", NormalizedUserName = "OWN", DisplayName = "本院管理员",
|
|
CollegeId = ownCollege.Id
|
|
};
|
|
var otherUser = new ApplicationUser
|
|
{
|
|
UserName = "other", NormalizedUserName = "OTHER", DisplayName = "外院管理员",
|
|
CollegeId = otherCollege.Id
|
|
};
|
|
db.AddRange(ownCollege, otherCollege, ownUser, otherUser);
|
|
db.DataImportBatches.AddRange(
|
|
Batch("own.xlsx", ownUser.Id, ownCollege.Id),
|
|
Batch("other.xlsx", otherUser.Id, otherCollege.Id));
|
|
await db.SaveChangesAsync();
|
|
|
|
var controller = new DataQualityController(
|
|
db, new FixedScope(ownUser.Id, ownCollege.Id));
|
|
var response = Assert.IsType<OkObjectResult>(await controller.GetBatches(
|
|
cancellationToken: CancellationToken.None));
|
|
var json = JsonSerializer.SerializeToElement(response.Value);
|
|
|
|
Assert.Equal(1, json.GetProperty("Total").GetInt32());
|
|
Assert.Equal("own.xlsx", json.GetProperty("Items")[0]
|
|
.GetProperty("FileName").GetString());
|
|
}
|
|
|
|
private static DataImportBatch Batch(
|
|
string fileName,
|
|
Guid userId,
|
|
Guid collegeId) => new()
|
|
{
|
|
Module = "base-data",
|
|
Target = "catalog",
|
|
FileName = fileName,
|
|
FileSize = 100,
|
|
FileSha256 = new string('a', 64),
|
|
CreatedByUserId = userId,
|
|
CollegeId = collegeId,
|
|
Status = DataImportBatchStatus.Succeeded,
|
|
TotalRows = 1,
|
|
CreatedCount = 1,
|
|
CompletedAt = DateTime.UtcNow
|
|
};
|
|
|
|
private sealed class FixedScope(Guid userId, Guid collegeId)
|
|
: ICurrentUserDataScope
|
|
{
|
|
public CurrentUserScope Current { get; } = new(
|
|
userId, "本院管理员", collegeId, DataScope.College,
|
|
new HashSet<string>([SystemRoles.CollegeAdmin]));
|
|
}
|
|
}
|