ファイル

448 行
17 KiB
C#

using System.Text.Json;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Project;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree.Tests;
public sealed class UndoTreeRestoreTests
{
const string OpenHash = "H0";
const string MidHash = "H2";
static UndoTreeHistory Track(UndoRedoManager manager, IUndoRedoable root)
=> new(manager, new AsyncAwaitStatus(), [root], 100, UndoRedoManagerReader.Create(manager));
static (UndoRedoManager Manager, Document Document, UndoTreeHistory History) Open(int x = 0, int y = 0, params string[] parts)
{
var document = new Document { X = x, Y = y };
foreach (var label in parts)
document.Parts.Add(new Part(label));
var manager = new UndoRedoManager();
manager.Subscribe(document);
return (manager, document, Track(manager, document));
}
static IReadOnlyList<UndoTreeNodeViewModel> Archive(UndoTreeHistory history)
{
var json = JsonSerializer.Serialize(history.ToRecord());
var nodes = UndoTreeArchive.Restore(JsonSerializer.Deserialize<UndoTreeRecord>(json)!);
nodes[0].ProjectHash = OpenHash;
return nodes;
}
static async Task<IReadOnlyList<UndoTreeNodeViewModel>> Session()
{
var (manager, document, history) = Open(0, 0, "p");
using (history)
{
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => document.Y = 5);
await manager.UndoAsync();
Histories.Edit(manager, () => document.Parts.Add(new Part("q")));
var nodes = Archive(history);
nodes.Single(node => node.Label == "Document / Y").ProjectHash = MidHash;
return nodes;
}
}
static UndoTreeNodeViewModel Node(IReadOnlyList<UndoTreeNodeViewModel> nodes, string label) => nodes.Single(node => node.Label == label);
static UndoTreeNodeViewModel Branch(IReadOnlyList<UndoTreeNodeViewModel> nodes) => nodes.Single(node => node.Steps?.Any(step => step.Kind == nameof(StepKind.Collection)) == true);
[Fact]
public async Task ADescendantIsReachedByReplayingEveryOperationOnTheWayAsOneNode()
{
var nodes = await Session();
var (manager, document, history) = Open(0, 0, "p");
using var _ = history;
var plan = UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash);
var result = await history.RestoreAsync(plan);
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(2, result.Applied);
Assert.Equal((1, 5), (document.X, document.Y));
Assert.Equal(2, history.Count);
await manager.UndoAsync();
Assert.Equal((0, 0), (document.X, document.Y));
}
[Fact]
public async Task AnotherBranchIsReachedTheSameWay()
{
var nodes = await Session();
var (_, document, history) = Open(0, 0, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Branch(nodes), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 0), (document.X, document.Y));
Assert.Equal(["p", "q"], document.Parts.Select(part => part.Label));
}
[Fact]
public async Task AnAncestorOfTheSavedNodeIsReachedByUndoingTheOperations()
{
var nodes = await Session();
var (_, document, history) = Open(1, 5, "p");
using var _ = history;
var plan = UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / X"), MidHash);
var result = await history.RestoreAsync(plan);
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 0), (document.X, document.Y));
}
[Fact]
public async Task TheOtherBranchOfTheSavedNodeIsReachedByUndoingAndThenReplaying()
{
var nodes = await Session();
var (_, document, history) = Open(1, 5, "p");
using var _ = history;
var plan = UndoTreeRestorePlan.For(nodes, Branch(nodes), MidHash);
var result = await history.RestoreAsync(plan);
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 0), (document.X, document.Y));
Assert.Equal(["p", "q"], document.Parts.Select(part => part.Label));
}
[Fact]
public async Task TheSavedStateItselfNeedsNoOperationAndLeavesTheCursorAtTheRoot()
{
var nodes = await Session();
var (_, document, history) = Open(0, 0, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[0], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(0, result.Applied);
Assert.Equal(1, history.Count);
Assert.Equal((0, 0), (document.X, document.Y));
}
[Fact]
public async Task EditsMadeSinceTheProjectWasOpenedAreUndoneFirstBecauseTheRecordStartsFromTheSavedState()
{
var nodes = await Session();
var (manager, document, history) = Open(0, 0, "p");
using var _ = history;
Histories.Edit(manager, () => document.X = 3);
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal((1, 5), (document.X, document.Y));
}
[Fact]
public async Task TheNearestAnchorIsUsedWhenSeveralNodesMatchTheProject()
{
var nodes = await Session();
Node(nodes, "Document / Y").ProjectHash = OpenHash;
var plan = UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash);
Assert.True(plan.IsPossible);
Assert.Empty(plan.Undo);
Assert.Empty(plan.Redo);
}
[Fact]
public async Task AProjectThatDiffersFromTheRecordIsLeftUntouched()
{
var nodes = await Session();
var (manager, document, history) = Open(7, 0, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Conflict, result.Outcome);
Assert.Equal("X", result.Detail);
Assert.Equal((7, 0), (document.X, document.Y));
Assert.False(manager.IsUndoable);
Assert.False(manager.IsRedoable);
Assert.Equal(1, history.Count);
}
[Fact]
public async Task AFailureAfterSomeOperationsWereAppliedUndoesThemAll()
{
var nodes = await Session();
var (manager, document, history) = Open(0, 3, "p");
using var _ = history;
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Conflict, result.Outcome);
Assert.Equal("Y", result.Detail);
Assert.Equal(1, result.Applied);
Assert.Equal((0, 3), (document.X, document.Y));
Assert.False(manager.IsUndoable);
Assert.False(manager.IsRedoable);
}
[Fact]
public async Task ARootThatIsNotTheStateWhenTheProjectWasOpenedCannotBeRestoredInto()
{
var nodes = await Session();
var document = new Document();
document.Parts.Add(new Part("p"));
var manager = new UndoRedoManager { Capacity = 2 };
manager.Subscribe(document);
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => document.X = 2);
Assert.False(history.RootIsOpenState);
var result = await history.RestoreAsync(UndoTreeRestorePlan.For(nodes, Node(nodes, "Document / Y"), OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Unavailable, result.Outcome);
Assert.Equal(2, document.X);
}
[Fact]
public async Task ThePlanSaysWhyARestoreIsNotPossible()
{
var nodes = await Session();
var target = Node(nodes, "Document / Y");
Assert.Equal(UndoTreeRestoreBlock.NoProject, UndoTreeRestorePlan.For(nodes, target, string.Empty).Block);
Assert.Equal(UndoTreeRestoreBlock.NoAnchor, UndoTreeRestorePlan.For(nodes, target, "other").Block);
Assert.True(UndoTreeRestorePlan.For(nodes, target, OpenHash).IsPossible);
}
[Fact]
public void ANodeThatCannotBeReplayedBlocksEveryPathThroughIt()
{
var (manager, document, history) = Open();
using var _ = history;
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => manager.AddCommand(new UndoRedoActionCommand(() => { }, () => { })));
Histories.Edit(manager, () => document.Y = 2);
var nodes = Archive(history);
var plan = UndoTreeRestorePlan.For(nodes, nodes[^1], OpenHash);
Assert.Equal(UndoTreeRestoreBlock.NotReplayable, plan.Block);
Assert.Same(nodes[2], plan.Offending);
Assert.True(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash).IsPossible);
}
[Fact]
public async Task AnImmutableListIsRebuiltWithTheRecordedElements()
{
var (managerA, sheetA) = Histories.NewSheet("a", "b", "c");
using var historyA = Track(managerA, sheetA);
Histories.Edit(managerA, () => sheetA.Parts = sheetA.Parts.RemoveAt(1).Add(new Part("d")));
var nodes = Archive(historyA);
var (_, sheetB) = Histories.NewSheet("a", "b", "c");
var managerB = new UndoRedoManager();
managerB.Subscribe(sheetB);
using var historyB = Track(managerB, sheetB);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(["a", "c", "d"], sheetB.Parts.Select(part => part.Label));
}
[Fact]
public async Task ABatchOfOperationsIsUndoneInReverseOrder()
{
var (managerA, sheetA) = Histories.NewSheet("a", "b");
using var historyA = Track(managerA, sheetA);
Histories.Edit(managerA, () =>
{
sheetA.Parts = sheetA.Parts.Add(new Part("n"));
sheetA.Parts[^1].Value = 4;
});
var nodes = Archive(historyA);
nodes[1].ProjectHash = MidHash;
var sheetB = new Sheet();
var added = new Part("n") { Value = 4 };
sheetB.Seed([new Part("a"), new Part("b"), added]);
var managerB = new UndoRedoManager();
managerB.Subscribe(sheetB);
using var historyB = Track(managerB, sheetB);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[0], MidHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(["a", "b"], sheetB.Parts.Select(part => part.Label));
}
[Fact]
public async Task AnElementAddedAndChangedInOneEditComesBackWithItsValue()
{
var (managerA, documentA, historyA) = Open();
using (historyA)
{
Histories.Edit(managerA, () =>
{
var part = new Part("n");
documentA.Parts.Add(part);
part.Value = 3;
});
var nodes = Archive(historyA);
var (_, documentB, historyB) = Open();
using var _ = historyB;
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(["n:3"], documentB.Parts.Select(part => part.ToString()));
}
}
[Fact]
public async Task ACallOnAnAddedObjectDoesNotBlockUndoingTheAddition()
{
var stageA = new Stage();
var managerA = new UndoRedoManager();
managerA.Subscribe(stageA);
using var historyA = Track(managerA, stageA);
Histories.Edit(managerA, () =>
{
var speaker = new Speaker();
stageA.Speakers.Add(speaker);
managerA.AddCommand(new UndoRedoAsyncTaskCommand(speaker.SpeakAsync, speaker.SpeakAsync));
});
var nodes = Archive(historyA);
nodes[1].ProjectHash = MidHash;
var stageB = new Stage();
stageB.Speakers.Add(new Speaker());
var managerB = new UndoRedoManager();
managerB.Subscribe(stageB);
using var historyB = Track(managerB, stageB);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[0], MidHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Empty(stageB.Speakers);
}
[Fact]
public async Task AnOperationOfThePreviousHistoryIsReplayedOnTheCurrentState()
{
var nodes = await Session();
var (manager, document, history) = Open(3, 0, "p");
using var _ = history;
var result = await history.ApplyRecordedAsync([Node(nodes, "Document / Y")], ConflictPolicy.Skip, false);
Assert.Equal(1, result.Applied);
Assert.Empty(result.Conflicts);
Assert.Equal((3, 5), (document.X, document.Y));
Assert.Equal(2, history.Count);
await manager.UndoAsync();
Assert.Equal((3, 0), (document.X, document.Y));
}
[Fact]
public async Task AValueThatDiffersFromTheRecordIsSkippedOrAppliedAccordingToThePolicy()
{
var nodes = await Session();
var (_, skipped, skipping) = Open(0, 3, "p");
using var first = skipping;
var (_, applied, applying) = Open(0, 3, "p");
using var second = applying;
var skip = await skipping.ApplyRecordedAsync([Node(nodes, "Document / Y")], ConflictPolicy.Skip, false);
var apply = await applying.ApplyRecordedAsync([Node(nodes, "Document / Y")], ConflictPolicy.Apply, false);
Assert.Equal(0, skip.Applied);
Assert.Equal(1, skip.Skipped);
Assert.Equal(3, skipped.Y);
Assert.Equal(1, apply.Applied);
Assert.Equal(0, apply.Skipped);
Assert.True(Assert.Single(apply.Conflicts).Resolved);
Assert.Equal(5, applied.Y);
}
[Fact]
public async Task AnOperationOfThePreviousHistoryCanBeRevertedFromTheCurrentState()
{
var nodes = await Session();
var (_, document, history) = Open(1, 5, "p");
using var _ = history;
var result = await history.ApplyRecordedAsync([Node(nodes, "Document / Y")], ConflictPolicy.Skip, true);
Assert.Equal(1, result.Applied);
Assert.Equal((1, 0), (document.X, document.Y));
}
[Fact]
public async Task ATargetThatDoesNotExistInTheCurrentProjectIsReportedAsDead()
{
var (managerA, documentA, historyA) = Open(0, 0, "p");
using (historyA)
{
Histories.Edit(managerA, () => documentA.Parts[0].Value = 4);
var nodes = Archive(historyA);
var (_, documentB, historyB) = Open();
using var _ = historyB;
var result = await historyB.ApplyRecordedAsync([nodes[1]], ConflictPolicy.Apply, false);
Assert.Equal(0, result.Applied);
var conflict = Assert.Single(result.Conflicts);
Assert.Equal(ConflictKind.DeadTarget, conflict.Kind);
Assert.False(conflict.Resolved);
Assert.Equal("Parts[0]", conflict.TargetLabel);
Assert.Equal("Value", conflict.Member);
Assert.Empty(documentB.Parts);
}
}
[Fact]
public async Task ARangeBecomesOneLiveNodePerRecordedNodeAndARootOrAnUnreplayableNodeIsRefused()
{
var nodes = await Session();
var (_, document, history) = Open(0, 0, "p");
using var _ = history;
var result = await history.ApplyRecordedAsync([Node(nodes, "Document / X"), Node(nodes, "Document / Y")], ConflictPolicy.Skip, false);
Assert.Equal(2, result.Applied);
Assert.Equal((1, 5), (document.X, document.Y));
Assert.Equal(3, history.Count);
await Assert.ThrowsAsync<UndoTreeOperationException>(() => history.ApplyRecordedAsync([nodes[0]], ConflictPolicy.Skip, false));
var unreplayable = UndoTreeArchive.Restore(new UndoTreeRecord(DateTime.Now, [new UndoTreeRecordNode(0, -1, string.Empty, DateTime.MinValue, []), new UndoTreeRecordNode(1, 0, "x", DateTime.Now, [])]));
await Assert.ThrowsAsync<UndoTreeOperationException>(() => history.ApplyRecordedAsync([unreplayable[1]], ConflictPolicy.Skip, false));
}
[Fact]
public async Task ARecordedCallIsInvokedOnTheMatchingObject()
{
var first = new Speaker();
var managerA = new UndoRedoManager();
managerA.Subscribe(first);
using var historyA = Track(managerA, first);
Histories.Edit(managerA, () => managerA.AddCommand(new UndoRedoAsyncTaskCommand(first.SpeakLaterAsync, first.SpeakLaterAsync)));
var nodes = Archive(historyA);
var second = new Speaker();
var managerB = new UndoRedoManager();
managerB.Subscribe(second);
using var historyB = Track(managerB, second);
var result = await historyB.RestoreAsync(UndoTreeRestorePlan.For(nodes, nodes[1], OpenHash));
Assert.Equal(UndoTreeRestoreOutcome.Done, result.Outcome);
Assert.Equal(1, second.Calls);
Assert.Equal(0, first.Calls);
}
}