AccountingNext/Schaad.Accounting.Tests/DataMigratorTestShould.cs
Claudio Schaad cbc1cd3f1f Restructure data folder to {mandator}/{year}, uploads and backup at root
New layout below DataPath (defined in DataFolders):
  {mandator}/{year}/*.json
  uploads/{mandator}/{year}/
  backup/{mandator}/{year}/

XmlToJsonMigrator becomes DataMigrator with two phases: first move the old
{year}/{mandator}/Data, uploads and {year}/backup folders into the new layout
unchanged, then convert the XML data files to JSON. Nothing is overwritten;
an identical file at the target is dropped, a different one stops startup.
Old folders are removed only once empty.

SettingsService builds the new paths; GetYearMandatorPath and
GetLastYearMandatorPath are removed as they now equal the data paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:57:58 +02:00

299 lines
12 KiB
C#

using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using Schaad.Accounting.Interfaces;
using Schaad.Accounting.Repositories;
using Shouldly;
namespace Schaad.Accounting.Tests;
public class DataMigratorTestShould : IDisposable
{
// Shaped like a file written by the old XmlSerializer-based repository, including the
// BOM-less declaration, namespaces and an xsi:nil FxRate.
private const string TransactionsXml = """
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfTransaction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Transaction>
<Id>t1</Id>
<ValueDate>2026-01-30T00:00:00</ValueDate>
<BookingDate>2026-01-31T00:00:00</BookingDate>
<Text>Gebäudeversicherung</Text>
<Value>114.20</Value>
<OriginAccountId>a1</OriginAccountId>
<TargetAccountId>a2</TargetAccountId>
<FxRate xsi:nil="true" />
</Transaction>
<Transaction>
<Id>t2</Id>
<ValueDate>2026-02-01T00:00:00</ValueDate>
<BookingDate>2026-02-01T00:00:00</BookingDate>
<Text>EUR Zahlung</Text>
<Value>-50.5</Value>
<OriginAccountId>a2</OriginAccountId>
<TargetAccountId>a1</TargetAccountId>
<FxRate>0.9312</FxRate>
</Transaction>
</ArrayOfTransaction>
""";
private const string AccountsXml = """
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfAccount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Account>
<Id>a1</Id>
<Number>1020</Number>
<Name>Bank</Name>
<Currency>CHF</Currency>
<StartBalance>1000.50</StartBalance>
<LastBankBalance>0</LastBankBalance>
</Account>
</ArrayOfAccount>
""";
private readonly string dataPath;
// Old layout: {year}/{mandator}/Data
private readonly string oldDataDir;
// New layout: {mandator}/{year}
private readonly string newDataDir;
private readonly DataMigrator sut = new(NullLogger<DataMigrator>.Instance);
public DataMigratorTestShould()
{
dataPath = Path.Combine(Path.GetTempPath(), "AccountingNext-tests-" + Guid.NewGuid().ToString("N"));
oldDataDir = Path.Combine(dataPath, "2026", "Mandator", "Data");
newDataDir = Path.Combine(dataPath, "Mandator", "2026");
Directory.CreateDirectory(dataPath);
}
public void Dispose()
{
if (Directory.Exists(dataPath))
{
Directory.Delete(dataPath, recursive: true);
}
}
private static void WriteFile(string path, string content)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, content);
}
private string[] XmlBackups(string fileName)
=> Directory.GetFiles(Path.Combine(dataPath, "backup", "Mandator", "2026"), fileName, SearchOption.AllDirectories);
[Fact]
public async Task ConvertOldLayoutXmlToJsonInMandatorYearFolderWhenMigrating()
{
WriteFile(Path.Combine(oldDataDir, "Transactions.xml"), TransactionsXml);
var result = await sut.MigrateAsync(dataPath);
result.ShouldBe(new DataMigrator.Result(MovedFiles: 1, ConvertedFiles: 1));
File.Exists(Path.Combine(newDataDir, "Transactions.json")).ShouldBeTrue();
File.Exists(Path.Combine(newDataDir, "Transactions.xml")).ShouldBeFalse();
Directory.Exists(Path.Combine(dataPath, "2026")).ShouldBeFalse();
var backup = XmlBackups("Transactions.xml");
backup.Length.ShouldBe(1);
File.ReadAllText(backup[0]).ShouldBe(TransactionsXml);
}
[Fact]
public async Task MoveOldLayoutJsonUnchangedWhenMigrating()
{
WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]");
var result = await sut.MigrateAsync(dataPath);
result.ShouldBe(new DataMigrator.Result(MovedFiles: 1, ConvertedFiles: 0));
File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[]");
Directory.Exists(Path.Combine(dataPath, "2026")).ShouldBeFalse();
}
[Fact]
public async Task MoveUploadsWithSubfoldersToRootUploadsFolderWhenMigrating()
{
var oldUploads = Path.Combine(dataPath, "2025", "Mandator", "uploads");
WriteFile(Path.Combine(oldUploads, "statement.c053.xml"), "<Document />");
WriteFile(Path.Combine(oldUploads, "creditCard", "card.pdf"), "pdf");
await sut.MigrateAsync(dataPath);
var newUploads = Path.Combine(dataPath, "uploads", "Mandator", "2025");
File.ReadAllText(Path.Combine(newUploads, "statement.c053.xml")).ShouldBe("<Document />");
File.ReadAllText(Path.Combine(newUploads, "creditCard", "card.pdf")).ShouldBe("pdf");
Directory.Exists(Path.Combine(dataPath, "2025")).ShouldBeFalse();
}
[Fact]
public async Task MoveYearBackupsToRootBackupFolderWhenMigrating()
{
WriteFile(Path.Combine(dataPath, "2024", "backup", "Mandator", "20240101120000.zip"), "zip");
await sut.MigrateAsync(dataPath);
File.ReadAllText(Path.Combine(dataPath, "backup", "Mandator", "2024", "20240101120000.zip")).ShouldBe("zip");
Directory.Exists(Path.Combine(dataPath, "2024")).ShouldBeFalse();
}
[Fact]
public async Task ConvertXmlAlreadyInNewLayoutWhenMigrating()
{
WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml);
var result = await sut.MigrateAsync(dataPath);
result.ShouldBe(new DataMigrator.Result(MovedFiles: 0, ConvertedFiles: 1));
File.Exists(Path.Combine(newDataDir, "Accounts.json")).ShouldBeTrue();
XmlBackups("Accounts.xml").Length.ShouldBe(1);
}
[Fact]
public async Task WriteHumanReadableJsonWhenConvertingXml()
{
WriteFile(Path.Combine(oldDataDir, "Transactions.xml"), TransactionsXml);
await sut.MigrateAsync(dataPath);
var json = File.ReadAllText(Path.Combine(newDataDir, "Transactions.json"));
json.ShouldContain("\"Text\": \"Gebäudeversicherung\"", Case.Sensitive);
json.ShouldContain("\n \"Id\": \"t1\"", Case.Sensitive);
json.ShouldNotContain("FxRate\": null", Case.Insensitive);
json.ShouldNotContain("ReadOnly", Case.Insensitive);
}
[Fact]
public async Task PreserveAllValuesWhenReadingMigratedDataThroughRepository()
{
WriteFile(Path.Combine(oldDataDir, "Transactions.xml"), TransactionsXml);
WriteFile(Path.Combine(oldDataDir, "Accounts.xml"), AccountsXml);
await sut.MigrateAsync(dataPath);
var settingsService = Substitute.For<ISettingsService>();
settingsService.GetDbPath().Returns(newDataDir);
settingsService.GetLastYearDbPath().Returns(Path.Combine(dataPath, "no-such-dir"));
var accountRepository = new AccountRepository(settingsService, new RepositoryCache(), NullLogger<AccountRepository>.Instance);
var transactionRepository = new TransactionRepository(settingsService, new RepositoryCache(), accountRepository, NullLogger<TransactionRepository>.Instance);
var transactions = await transactionRepository.GetTransactionListAsync();
var accounts = await accountRepository.GetAccountListAsync();
transactions.Count.ShouldBe(2);
transactions[0].Text.ShouldBe("Gebäudeversicherung");
transactions[0].Value.ShouldBe(114.20m);
transactions[0].ValueDate.ShouldBe(new DateTime(2026, 1, 30));
transactions[0].BookingDate.ShouldBe(new DateTime(2026, 1, 31));
transactions[0].OriginAccountId.ShouldBe("a1");
transactions[0].TargetAccountId.ShouldBe("a2");
transactions[0].FxRate.ShouldBeNull();
transactions[1].Value.ShouldBe(-50.5m);
transactions[1].FxRate.ShouldBe(0.9312m);
accounts.Single().Number.ShouldBe(1020);
accounts.Single().StartBalance.ShouldBe(1000.50m);
}
[Fact]
public async Task LeaveUnknownXmlFilesUnconvertedWhenMigrating()
{
WriteFile(Path.Combine(newDataDir, "camt053.xml"), "<Document />");
WriteFile(Path.Combine(dataPath, "uploads", "Mandator", "2026", "Accounts.xml"), "<Document />");
var result = await sut.MigrateAsync(dataPath);
result.ConvertedFiles.ShouldBe(0);
File.Exists(Path.Combine(newDataDir, "camt053.xml")).ShouldBeTrue();
File.Exists(Path.Combine(dataPath, "uploads", "Mandator", "2026", "Accounts.xml")).ShouldBeTrue();
}
[Fact]
public async Task DoNothingWhenAlreadyMigrated()
{
WriteFile(Path.Combine(oldDataDir, "Accounts.xml"), AccountsXml);
await sut.MigrateAsync(dataPath);
var result = await sut.MigrateAsync(dataPath);
result.ShouldBe(new DataMigrator.Result(0, 0));
}
[Fact]
public async Task KeepOldFolderWithUnexpectedFilesWhenMigrating()
{
WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]");
var stray = Path.Combine(dataPath, "2026", "Mandator", "notes.txt");
WriteFile(stray, "keep me");
await sut.MigrateAsync(dataPath);
File.Exists(Path.Combine(newDataDir, "Accounts.json")).ShouldBeTrue();
File.ReadAllText(stray).ShouldBe("keep me");
Directory.Exists(oldDataDir).ShouldBeFalse();
}
[Fact]
public async Task DropOldFileWhenIdenticalFileAlreadyMoved()
{
// Simulates a crash after a copy landed in the new layout but before the old one was removed.
WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]");
WriteFile(Path.Combine(newDataDir, "Accounts.json"), "[]");
await sut.MigrateAsync(dataPath);
File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[]");
Directory.Exists(Path.Combine(dataPath, "2026")).ShouldBeFalse();
}
[Fact]
public async Task ThrowAndSkipConversionWhenMoveTargetHasDifferentContent()
{
WriteFile(Path.Combine(oldDataDir, "Accounts.json"), "[]");
WriteFile(Path.Combine(newDataDir, "Accounts.json"), "[{}]");
WriteFile(Path.Combine(newDataDir, "Transactions.xml"), TransactionsXml);
await Should.ThrowAsync<AggregateException>(() => sut.MigrateAsync(dataPath));
File.ReadAllText(Path.Combine(oldDataDir, "Accounts.json")).ShouldBe("[]");
File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[{}]");
File.Exists(Path.Combine(newDataDir, "Transactions.xml")).ShouldBeTrue();
}
[Fact]
public async Task FinishConversionWhenJsonAlreadyMatchesXml()
{
// Simulates a crash after the JSON was written but before the XML was moved.
WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml);
await sut.MigrateAsync(dataPath);
WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml);
var result = await sut.MigrateAsync(dataPath);
result.ConvertedFiles.ShouldBe(1);
File.Exists(Path.Combine(newDataDir, "Accounts.xml")).ShouldBeFalse();
XmlBackups("Accounts*.xml").Length.ShouldBe(2);
}
[Fact]
public async Task ThrowAndKeepBothFilesWhenJsonExistsWithDifferentContent()
{
WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml);
WriteFile(Path.Combine(newDataDir, "Accounts.json"), "[]");
await Should.ThrowAsync<AggregateException>(() => sut.MigrateAsync(dataPath));
File.Exists(Path.Combine(newDataDir, "Accounts.xml")).ShouldBeTrue();
File.ReadAllText(Path.Combine(newDataDir, "Accounts.json")).ShouldBe("[]");
}
[Fact]
public async Task ConvertRemainingFilesAndThrowWhenOneXmlIsCorrupt()
{
WriteFile(Path.Combine(newDataDir, "Accounts.xml"), AccountsXml);
WriteFile(Path.Combine(newDataDir, "Transactions.xml"), "<ArrayOfTransaction><Transaction>");
await Should.ThrowAsync<AggregateException>(() => sut.MigrateAsync(dataPath));
File.Exists(Path.Combine(newDataDir, "Accounts.json")).ShouldBeTrue();
File.Exists(Path.Combine(newDataDir, "Transactions.xml")).ShouldBeTrue();
File.Exists(Path.Combine(newDataDir, "Transactions.json")).ShouldBeFalse();
}
}