Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions SemiStep/SemiStep.Tests/UI/MainWindow/MainWindowExitFlowTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,15 @@ public async Task HandleExitChoice_Save_SuccessfulSave_ClosesWindow()
[AvaloniaFact]
public async Task HandleExitChoice_Save_FailedCoordinatorSave_KeepsWindowOpen()
{
var driver = new RecipeTestDriver(_fixture.Session);
driver.AddFor(3).AddWait(1f);
_fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop");
_viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_tempFilePath));
await File.WriteAllTextAsync(_tempFilePath, "blocker");
var unwritablePath = Path.Combine(_tempFilePath, "recipe.csv");
_viewModel.RecipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(unwritablePath));

await _window.HandleExitChoiceAsync(UnsavedChangesChoice.Save);

_window.IsVisible.Should().BeTrue("a failed save must not discard the recipe by closing the window");
File.Exists(_tempFilePath).Should().BeFalse();
File.Exists(unwritablePath).Should().BeFalse();
_fixture.MessagePanel.Entries.Count(e => e.IsError).Should().Be(1, "the failed save is reported once");
}

[AvaloniaFact]
Expand Down
139 changes: 117 additions & 22 deletions SemiStep/SemiStep.Tests/UI/RecipeCoordinatorSaveGateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using SemiStep.Core.Plc;
using SemiStep.Core.Plc.Sync.Ownership;
using SemiStep.Core.Recipes;
using SemiStep.Core.Recipes.Analysis.Warnings;
using SemiStep.Core.Recipes.Clipboard;
using SemiStep.Core.Recipes.Import;
using SemiStep.Tests.Core.Helpers;
Expand All @@ -30,39 +31,112 @@ public sealed class RecipeCoordinatorSaveGateTests
private const string TempFilePrefix = "SemiStep.CoordinatorSaveGate";

[AvaloniaFact]
public async Task Save_OnDefectiveRecipe_FailsAndWritesNoFile()
public async Task Save_RecipeWithUnclosedLoop_SavesAndReopensWithSameWarnings()
{
var (coordinator, panel, session) = await BuildCoordinatorAsync();
var tempFilePath = Path.Combine(Path.GetTempPath(), $"{TempFilePrefix}.{Guid.NewGuid():N}.csv");
var warnings = await SaveAndReopenAsync(driver => driver.AddWait(1f).AddFor(3).AddWait(1f));

warnings.Should().Equal((typeof(UnclosedForLoopWarning), 2));
}

[AvaloniaFact]
public async Task Save_RecipeWithUnmatchedLoopEnd_SavesAndReopensWithSameWarnings()
{
var warnings = await SaveAndReopenAsync(driver => driver.AddWait(1f).AddEndFor());

warnings.Should().Equal((typeof(UnmatchedEndForWarning), 2));
}

[AvaloniaFact]
public async Task Open_SavedRecipeWithWarnings_NotifiesSyncServiceAsInvalid()
{
var tempFilePath = NewTempFilePath();
var saving = await BuildCoordinatorAsync();
var reopening = await BuildCoordinatorAsync();

try
{
var driver = new RecipeTestDriver(session);
driver.AddFor(3).AddWait(1f);
new RecipeTestDriver(saving.Session).AddFor(3).AddWait(1f);
(await saving.Coordinator.SaveRecipeAsync(tempFilePath)).EnsureSuccess("Saving the defective recipe");

reopening.SyncService.SetSyncEnabled(true);
(await reopening.Coordinator.LoadRecipeAsync(tempFilePath)).EnsureSuccess("Opening the saved recipe");

reopening.SyncService.NotifyRecipeChangedCalls.Should().NotBeEmpty(
"opening a recipe with sync on hands it to the PLC sync service");
var lastNotification = reopening.SyncService.NotifyRecipeChangedCalls[^1];
lastNotification.Recipe.StepCount.Should().Be(2);
lastNotification.IsValid.Should().BeFalse(
"a recipe with warnings saves to a file but must not be written to the PLC");
}
finally
{
saving.Dispose();
reopening.Dispose();
DeleteIfExists(tempFilePath);
}
}

private static async Task<List<(Type Type, int StepNumber)>> SaveAndReopenAsync(
Action<RecipeTestDriver> buildDefectiveRecipe)
{
var tempFilePath = NewTempFilePath();
var saving = await BuildCoordinatorAsync();
var reopening = await BuildCoordinatorAsync();

try
{
buildDefectiveRecipe(new RecipeTestDriver(saving.Session));
saving.Session.IsValid.Should().BeFalse("the fixture recipe carries a loop warning");
var savedWarnings = LoopWarnings(saving.Session);

var saveResult = await saving.Coordinator.SaveRecipeAsync(tempFilePath);

session.IsValid.Should().BeFalse("the recipe has an unclosed For loop");
saveResult.IsSuccess.Should().BeTrue("a recipe with warnings must save");
File.Exists(tempFilePath).Should().BeTrue();
saving.Session.IsDirty.Should().BeFalse("a successful save marks the recipe saved");

var result = await coordinator.SaveRecipeAsync(tempFilePath);
var loadResult = await reopening.Coordinator.LoadRecipeAsync(tempFilePath);

result.IsFailed.Should().BeTrue("Save must reject a recipe with structural defects");
File.Exists(tempFilePath).Should().BeFalse("the file must not be written when Save is rejected");
panel.Entries.Should().ContainSingle(
e => e.IsWarning,
"the underlying analyzer warning must still surface in the message panel after the rejected Save");
loadResult.IsSuccess.Should().BeTrue("the saved file must open again");
reopening.Session.Current.StepCount.Should().Be(saving.Session.Current.StepCount);
reopening.Panel.WarningCount.Should().Be(1, "the reopened recipe shows its one loop warning");
var reopenedWarnings = LoopWarnings(reopening.Session);
reopenedWarnings.Should().Equal(savedWarnings);

return reopenedWarnings;
}
finally
{
coordinator.Dispose();
panel.Dispose();
if (File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
saving.Dispose();
reopening.Dispose();
DeleteIfExists(tempFilePath);
}
}

private static List<(Type Type, int StepNumber)> LoopWarnings(RecipeSession session)
{
var unclosed = session.Snapshot.Reasons.OfType<UnclosedForLoopWarning>()
.Select(warning => (warning.GetType(), warning.StepNumber));
var unmatched = session.Snapshot.Reasons.OfType<UnmatchedEndForWarning>()
.Select(warning => (warning.GetType(), warning.StepNumber));

return [.. unclosed, .. unmatched];
}

private static string NewTempFilePath()
{
return Path.Combine(Path.GetTempPath(), $"{TempFilePrefix}.{Guid.NewGuid():N}.csv");
}

private static void DeleteIfExists(string path)
{
if (File.Exists(path))
{
File.Delete(path);
}
}

private static async Task<(RecipeCoordinator Coordinator, MessagePanelViewModel Panel, RecipeSession Session)>
BuildCoordinatorAsync()
private static async Task<CoordinatorFixture> BuildCoordinatorAsync()
{
var configDir = TestConfigLocator.GetConfigDirectory("WithGroups");
var configLoadResult = await ConfigFacade.LoadAndValidateAsync(configDir);
Expand All @@ -78,7 +152,8 @@ public async Task Save_OnDefectiveRecipe_FailsAndWritesNoFile()
.AddSingleton<IS7Connection>(sp => sp.GetRequiredService<StubS7Service>())
.AddSingleton<IS7Reader>(sp => sp.GetRequiredService<StubS7Service>())
.AddSingleton<IS7ExecutionStream>(sp => sp.GetRequiredService<StubS7Service>())
.AddSingleton<IPlcSyncService, StubPlcSyncService>()
.AddSingleton<StubPlcSyncService>()
.AddSingleton<IPlcSyncService>(sp => sp.GetRequiredService<StubPlcSyncService>())
.AddSingleton<IPlcSyncOwnership, StubPlcSyncOwnership>()
.BuildServiceProvider();

Expand All @@ -101,6 +176,26 @@ public async Task Save_OnDefectiveRecipe_FailsAndWritesNoFile()
NullLogger<RecipeCoordinator>.Instance);
coordinator.Initialize();

return (coordinator, panel, session);
return new CoordinatorFixture(
coordinator,
panel,
session,
services.GetRequiredService<StubPlcSyncService>(),
services);
}

private sealed record CoordinatorFixture(
RecipeCoordinator Coordinator,
MessagePanelViewModel Panel,
RecipeSession Session,
StubPlcSyncService SyncService,
ServiceProvider Services) : IDisposable
{
public void Dispose()
{
Coordinator.Dispose();
Panel.Dispose();
Services.Dispose();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,13 @@ public async Task New_Dirty_SaveAsCancelled_KeepsRecipe()
[AvaloniaFact]
public async Task New_Dirty_SaveFails_KeepsRecipe()
{
new RecipeTestDriver(_fixture.Session).AddFor(3);
_fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop");
var stepCountBefore = StepCount;
_answer = UnsavedChangesChoice.Save;
_saveAsAnswer = _savePath;
_saveAsAnswer = UnwritableSavePath;

await _recipeFile.NewRecipeCommand.Execute();

File.Exists(_savePath).Should().BeFalse();
File.Exists(UnwritableSavePath).Should().BeFalse();
StepCount.Should().Be(stepCountBefore, "a failed save aborts the new recipe");
_fixture.MessagePanel.Entries.Count(e => e.IsError).Should().Be(1, "the failed save is reported once");
}
Expand Down Expand Up @@ -241,17 +239,16 @@ public async Task Open_Dirty_SaveAsCancelled_KeepsRecipeWithoutPicker()
[AvaloniaFact]
public async Task Open_Dirty_SaveFails_KeepsRecipeWithoutPicker()
{
new RecipeTestDriver(_fixture.Session).AddFor(3);
_fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop");
var stepCountBefore = StepCount;
_answer = UnsavedChangesChoice.Save;
_saveAsAnswer = _savePath;
_saveAsAnswer = UnwritableSavePath;

await _recipeFile.LoadRecipeCommand.Execute();

File.Exists(_savePath).Should().BeFalse();
File.Exists(UnwritableSavePath).Should().BeFalse();
_openPickerCount.Should().Be(0, "a failed save aborts the open");
StepCount.Should().Be(stepCountBefore);
_fixture.MessagePanel.Entries.Count(e => e.IsError).Should().Be(1, "the failed save is reported once");
}

[AvaloniaFact]
Expand Down Expand Up @@ -310,6 +307,9 @@ public async Task Open_Clean_OpensPickedFileWithoutPrompt()

private int StepCount => _fixture.Coordinator.CurrentRecipe.StepCount;

/// <summary>A path below an existing file, so the file system rejects the write.</summary>
private string UnwritableSavePath => Path.Combine(_openPath, "recipe.csv");

private async Task<int> SavedStepCountAsync(string path)
{
File.Exists(path).Should().BeTrue();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,10 @@ public async Task LoadRecipe_CleanFile_SurfacesSuccessEntryWithoutWarning()
[AvaloniaFact]
public async Task LoadRecipe_StructurallyWarnedRecipeFromCleanFile_KeepsLoadedSuccessInOperationSlot()
{
// A structurally-warned recipe (an unclosed For) is saved DIRECTLY through the CSV service,
// bypassing the coordinator save gate that rejects invalid recipes. The file itself is clean
// (correct ROWS header), so the load produces no integrity warning: the operation slot must
// still show the "Loaded" success, with the structural warning confined to the validation list.
// A structurally-warned recipe (an unclosed For) is saved directly through the CSV service.
// The file itself is clean (correct ROWS header), so the load produces no integrity warning:
// the operation slot must still show the "Loaded" success, with the structural warning
// confined to the validation list.
var driver = new RecipeTestDriver(_fixture.Session);
driver.AddFor(3);
_fixture.Session.IsValid.Should().BeFalse("an unclosed For loop is a structural defect");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

using Microsoft.Extensions.Logging.Abstractions;

using SemiStep.Tests.Core.Helpers;
using SemiStep.Tests.UI.Helpers;

using SemiStep.UI.Localization;
Expand Down Expand Up @@ -45,6 +44,11 @@ public async ValueTask DisposeAsync()
{
File.Delete(_tempFilePath);
}

if (Directory.Exists(_tempFilePath))
{
Directory.Delete(_tempFilePath, recursive: true);
}
}

[AvaloniaFact]
Expand All @@ -62,16 +66,15 @@ public async Task SaveRecipe_Success_EmitsTrueAndSetsCurrentFilePath()
[AvaloniaFact]
public async Task SaveRecipe_FailedCoordinatorSave_EmitsFalseAndKeepsCurrentFilePathUnset()
{
var driver = new RecipeTestDriver(_fixture.Session);
driver.AddFor(3).AddWait(1f);
_fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop");
_recipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(_tempFilePath));
await File.WriteAllTextAsync(_tempFilePath, "blocker");
var unwritablePath = Path.Combine(_tempFilePath, "recipe.csv");
_recipeFile.SaveFileInteraction.RegisterHandler(context => context.SetOutput(unwritablePath));

var saved = await _recipeFile.SaveRecipeCommand.Execute();

saved.Should().BeFalse("the coordinator rejects saving a structurally defective recipe");
saved.Should().BeFalse("the file system rejects a path below an existing file");
_recipeFile.CurrentFilePath.Should().BeNull("a failed save must not adopt the target path");
File.Exists(_tempFilePath).Should().BeFalse();
File.Exists(unwritablePath).Should().BeFalse();
}

[AvaloniaFact]
Expand Down Expand Up @@ -140,9 +143,8 @@ public async Task SaveRecipe_WithCurrentFilePath_FailedCoordinatorSave_EmitsFals
context.SetOutput(_tempFilePath);
});
(await _recipeFile.SaveRecipeCommand.Execute()).Should().BeTrue("the arrange save establishes the file path");
var driver = new RecipeTestDriver(_fixture.Session);
driver.AddFor(3).AddWait(1f);
_fixture.Session.IsValid.Should().BeFalse("the recipe has an unclosed For loop");
File.Delete(_tempFilePath);
Directory.CreateDirectory(_tempFilePath);

var saved = await _recipeFile.SaveRecipeCommand.Execute();

Expand Down
11 changes: 0 additions & 11 deletions SemiStep/SemiStep.UI/Coordinator/RecipeCoordinator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -369,17 +369,6 @@ public async Task<Result> SaveRecipeAsync(string filePath)
filePath,
_session.Current.StepCount);

if (!_session.IsValid)
{
const string SaveRejectionMessage = "Cannot save recipe with structural defects (see warnings in the message panel).";
_logger.LogWarning(
"Save rejected: recipe is not valid. StepCount={StepCount}",
_session.Current.StepCount);
var rejection = Result.Fail(SaveRejectionMessage).WithReasons(_session.Snapshot.Reasons);
RebuildMessagePanel();
return rejection;
}

var result = await _csvService.SaveAsync(_session.Current, filePath);

if (result.IsFailed)
Expand Down
2 changes: 2 additions & 0 deletions docs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,8 @@ _Окно установки RIE в транспонированном пред
- отображается понятное сообщение;
- запрещается сохранение/отправка рецепта в ПЛК до исправления ошибок.

Рецепт с предупреждениями о циклах (цикл без конца или конец цикла без начала) сохраняется в файл и открывается снова с теми же предупреждениями. В ПЛК такой рецепт не записывается, пока предупреждения не устранены.

---

### 3.6. Импорт CSV
Expand Down