Skip to content
This repository has been archived by the owner on Sep 3, 2024. It is now read-only.

Commit

Permalink
feat: state manager singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
julien-wff committed Dec 3, 2023
1 parent b8c77ee commit 6652002
Show file tree
Hide file tree
Showing 2 changed files with 98 additions and 0 deletions.
31 changes: 31 additions & 0 deletions EasyLib/Files/StateManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
namespace EasyLib.Files;

/// <summary>
/// Singleton to get and write the jobs to the state.json file.
/// </summary>
public class StateManager
{
public readonly string StateFilePath;

private StateManager()
{
// AppData dir and append easysave/state.json
var appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var stateDirectory = Path.Combine(appDataDir, "easysave");
StateFilePath = Path.Combine(stateDirectory, "state.json");

// Create directory if it doesn't exist
if (!Directory.Exists(stateDirectory))
{
Directory.CreateDirectory(stateDirectory);
}

// Create file and write [] if it doesn't exist
if (!File.Exists(StateFilePath))
{
File.WriteAllText(StateFilePath, "[]");
}
}

public static StateManager Instance { get; } = new();
}
67 changes: 67 additions & 0 deletions EasySave.Tests/EasyLib/Files/StateManagerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using EasyLib.Files;

namespace EasySave.Tests.EasyLib.Files;

public class StateManagerTests
{
private string GetStateFilePath()
{
var appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var stateDirectory = Path.Combine(appDataDir, "easysave");
return Path.Combine(stateDirectory, "state.json");
}

[Fact]
public void Instance_ShouldBeSingleton()
{
// Arrange

// Act
var instance1 = StateManager.Instance;
var instance2 = StateManager.Instance;

// Assert
Assert.Same(instance1, instance2);
}

[Fact]
public void StateFileCreation_ShouldCreateEmptyFile()
{
// Arrange

// Act
var stateManager = StateManager.Instance;
var stateFilePath = stateManager.StateFilePath;

// Assert
Assert.True(File.Exists(stateFilePath));
}

[Fact]
public void StateFileCreation_ShouldCreateJsonArray()
{
// Arrange

// Act
var stateManager = StateManager.Instance;
var stateFilePath = stateManager.StateFilePath;
var fileContent = File.ReadAllText(stateFilePath).Trim();

// Assert
Assert.StartsWith("[", fileContent);
Assert.EndsWith("]", fileContent);
}

[Fact]
public void StateFilePath_ShouldBeCorrect()
{
// Arrange

// Act
var stateManager = StateManager.Instance;
var stateFilePath = stateManager.StateFilePath;

// Assert
Assert.Equal(GetStateFilePath(), stateFilePath);
}
}

0 comments on commit 6652002

Please sign in to comment.