Skip to content

Commit

Permalink
Removed unnecessary methods and updated descriptions and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
kubagdynia committed Dec 2, 2023
1 parent 8a1c31f commit ec57717
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 80 deletions.
27 changes: 18 additions & 9 deletions CacheDrive.Tests/CachingObjectsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public void SetUp()
[Test]
public async Task ObjectShouldBeProperlyCachedAndRestoredFromTheMemory()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(
DateTime.Now,
cacheEnabled: true,
Expand All @@ -37,17 +38,21 @@ public async Task ObjectShouldBeProperlyCachedAndRestoredFromTheMemory()

await cacheService.InitializeAsync();

// Act
await cacheService.SetAsync(_testClass.Id.ToString(), _testClass);

var cachedTestClass = await cacheService.GetAsync<TestClass>(_testClass.Id.ToString());

await cacheService.FlushAsync();

// Assert
cachedTestClass.Should().BeEquivalentTo(_testClass);
}

[Test, Order(1)]
public async Task ObjectShoulBeProperlyCachedInMemoryAndPersistedToTheFile()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(
DateTime.Now,
cacheEnabled: true,
Expand All @@ -59,17 +64,21 @@ public async Task ObjectShoulBeProperlyCachedInMemoryAndPersistedToTheFile()

await cacheService.InitializeAsync();

// Act
await cacheService.SetAsync(_testClass.Id.ToString(), _testClass);

var cachedTestClass = await cacheService.GetAsync<TestClass>(_testClass.Id.ToString());

await cacheService.FlushAsync();

// Assert
cachedTestClass.Should().BeEquivalentTo(_testClass);
}

[Test, Order(2)]
public async Task CacheShouldBeProperlyLoadedFromTheFile_Then_ObjectShouldBeProperlyRestoredFromTheMemory()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(
DateTime.Now,
cacheEnabled: true,
Expand All @@ -80,16 +89,20 @@ public async Task CacheShouldBeProperlyLoadedFromTheFile_Then_ObjectShouldBeProp
ICacheService cacheService = serviceProvider.GetRequiredService<ICacheService>();

await cacheService.InitializeAsync();


// Act
var cachedTestClass = await cacheService.GetAsync<TestClass>(_testClass.Id.ToString());

await cacheService.FlushAsync();

// Assert
cachedTestClass.Should().BeEquivalentTo(_testClass);
}

[Test, Order(3)]
public async Task CacheShouldExpiredDuringLoadedFromTheFile_Then_ObjectShouldNotBeProperlyRestoredFromTheMemory()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(
DateTime.Now.AddHours(3),
cacheEnabled: true,
Expand All @@ -101,13 +114,16 @@ public async Task CacheShouldExpiredDuringLoadedFromTheFile_Then_ObjectShouldNot

await cacheService.InitializeAsync();

// Act
var cachedTestClass = await cacheService.GetAsync<TestClass>(_testClass.Id.ToString());

await cacheService.FlushAsync();

// Assert
cachedTestClass.Should().BeNull();
}

private class TestClass : ICacheable
private class TestClass
{
[JsonPropertyName("id")]
public Guid Id { get; set; }
Expand All @@ -120,12 +136,5 @@ private class TestClass : ICacheable

[JsonPropertyName("age")]
public int Age { get; set; }

[JsonIgnore]
public string CacheKey
=> GetCacheKey(Id.ToString());

public static string GetCacheKey(string key)
=> $"{nameof(TestClass)}@{key}";
}
}
8 changes: 1 addition & 7 deletions CacheDrive.Tests/CachingSimpleTypesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ public async Task SimpleTypesShouldBeProperlyCachedAndRestoredFromTheMemory()
(string key, bool value) boolItem = ("bool_test", true);
await cacheService.SetAsync(boolItem.key, boolItem.value);


int cachedIntItem = await cacheService.GetAsync<int>(intItem.key);
char cachedCharItem = await cacheService.GetAsync<char>(charItem.key);
float cachedFloatItem = await cacheService.GetAsync<float>(floatItem.key);
Expand All @@ -53,11 +52,6 @@ public async Task SimpleTypesShouldBeProperlyCachedAndRestoredFromTheMemory()
cachedCharItem.Should().Be(charItem.value);
cachedFloatItem.Should().Be(floatItem.value);
cachedDoubleItem.Should().Be(doubleItem.value);
cachedBoolItem.Should().Be(boolItem.value);
}
}

public enum Tt
{
One,
Two
}
7 changes: 7 additions & 0 deletions CacheDrive.Tests/MemoryAndFileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,19 @@ public class MemoryAndFileTests
[Test, Order(1)]
public async Task CacheShouldBeSavedCorrectly()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(DateTime.Now);

ICacheService cacheService = serviceProvider.GetRequiredService<ICacheService>();

await cacheService.InitializeAsync();

// Act
string key = "name";

await cacheService.SetAsync(key, "John");

// Assert
if (cacheService.TryGetValue(key, out string cachedValue))
{
cachedValue.Should().Be("John");
Expand All @@ -35,13 +38,15 @@ public async Task CacheShouldBeSavedCorrectly()
[Test, Order(2)]
public async Task CacheShouldBeLoadCorrectly()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(DateTime.Now);

ICacheService cacheService = serviceProvider.GetRequiredService<ICacheService>();
await cacheService.InitializeAsync();

string key = "name";

// Assert
if (cacheService.TryGetValue(key, out string cachedValue))
{
cachedValue.Should().Be("John");
Expand All @@ -57,13 +62,15 @@ public async Task CacheShouldBeLoadCorrectly()
[Test, Order(3)]
public async Task CacheShouldExpired()
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(DateTime.Now.AddHours(3));

ICacheService cacheService = serviceProvider.GetRequiredService<ICacheService>();
await cacheService.InitializeAsync();

string key = "name";

// Assert
if (!cacheService.TryGetValue(key, out string _))
{
await cacheService.FlushAsync();
Expand Down
3 changes: 3 additions & 0 deletions CacheDrive.Tests/MemoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,21 @@ public class MemoryTests
[TestCase("key2","Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")]
public async Task StringShouldBeCorrectlySavedAndReadFromTheCacheInMemory(string key, string text)
{
// Arrange
ServiceProvider serviceProvider = TestHelper.CreateServiceProvider(DateTime.Now, true, CacheExpirationType.Hours, 2, CacheType.Memory);

ICacheService cacheService = serviceProvider.GetRequiredService<ICacheService>();

await cacheService.InitializeAsync();

// Act
await cacheService.SetAsync(key, text);

string resultValue = await cacheService.GetAsync<string>(key);

await cacheService.FlushAsync();

// Assert
resultValue.Should().Be(text);
}
}
2 changes: 2 additions & 0 deletions CacheDrive/Configuration/CacheSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ public class CacheSettings

public int CacheExpiration { get; set; } = 60;

public string CacheFolderName { get; set; } = "cache";

public CacheExpirationType CacheExpirationType { get; set; } = CacheExpirationType.Minutes;

public CacheType CacheType { get; set; } = CacheType.Memory;
Expand Down
2 changes: 1 addition & 1 deletion CacheDrive/ICacheable.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace CacheDrive;

public interface ICacheable
internal interface ICacheable
{
string CacheKey { get; }

Expand Down
55 changes: 44 additions & 11 deletions CacheDrive/Services/ICacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,69 @@ public interface ICacheService
/// Should be run before the cache is used, usually at application startup.
/// Can be used many times, each time adding or overwriting data if they have the same keys.
/// </summary>
/// <returns></returns>
Task InitializeAsync();

/// <summary>
/// Dumps cached data into files, database, and so on.
/// Usually it should be run before the application terminates.
/// Can be used many times, each time saving data that are new or has been changed.
/// </summary>
/// <returns></returns>
Task FlushAsync();

/// <summary>
/// Returns whether an object with the specified key exists in the cache.
/// </summary>
/// <param name="key">The key of the value to check.</param>
/// <returns>true if the key was found in the cache, otherwise, false.</returns>
bool HasItem(string key);

/// <summary>
/// Attempts to get the value associated with the specified key from the cache.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <param name="value">
/// When this method returns, value contains the object from
/// the cache with the specified key or the default value of
/// <typeparamref name="T"/>, if the operation failed.
/// </param>
/// <returns>true if the key was found in the cache, otherwise, false.</returns>
bool TryGetValue<T>(string key, out T value);


/// <summary>
/// Get the value associated with the specified key from the cache.
/// </summary>
/// <param name="key">The key of the value to get.</param>
/// <returns>The value contains the object from the cache with the specified
/// key or the default value of T, if the operation failed.
/// </returns>
Task<T> GetAsync<T>(string key);

void Set<T>(T item, int expirySeconds = 0) where T : ICacheable;

/// <summary>
/// Adds a value to the cache if the key does not already exist, or updates if the key already exists.
/// </summary>
/// <param name="key">The key to be added or whose value should be updated.</param>
/// <param name="value">The value to add or update.</param>
/// <param name="expirySeconds">After how many seconds a given value will expire in the cache. Optional parameter.
/// By default, the value is taken from the configuration.</param>
Task SetAsync<T>(string key, T value, int expirySeconds = 0);

Task SetAsync<T>(T item, int expirySeconds = 0) where T : ICacheable;

/// <summary>
/// Deletes the object associated with the given key.
/// </summary>
/// <param name="key">The key of the element to be remove.</param>
/// <returns>true if an object was removed successfully; otherwise, false.</returns>
bool Delete(string key);

/// <summary>
/// Deletes the object associated with the given key.
/// </summary>
/// <param name="key">The key of the element to be remove.</param>
/// <returns>true if an object was removed successfully; otherwise, false.</returns>
Task<bool> DeleteAsync(string key);

void DeletePrefix(string prefix);

Task DeletePrefixAsync(string prefix);

/// <summary>
/// Returns the number of items in the cache.
/// </summary>
/// <returns>The number of items in the cache.</returns>
int CountCacheItems();
}
6 changes: 2 additions & 4 deletions CacheDrive/Services/MemoryCacheFileStorageService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ namespace CacheDrive.Services;

internal class MemoryCacheFileStorageService : MemoryCacheService
{
private const string CacheFolderName = "cache";

public MemoryCacheFileStorageService(IOptions<CacheSettings> settings, IDateService dateService)
: base(settings, dateService)
{
Expand Down Expand Up @@ -74,10 +72,10 @@ private Regex SafeFilenameRegex()
}

private string CachePath(string fileName)
=> Path.Combine(Environment.CurrentDirectory, CacheFolderName, fileName);
=> Path.Combine(Environment.CurrentDirectory, CacheSettings.CacheFolderName, fileName);

private string GetCacheDirectory()
=> Path.Combine(Environment.CurrentDirectory, CacheFolderName);
=> Path.Combine(Environment.CurrentDirectory, CacheSettings.CacheFolderName);

private void CreateCacheDirectory()
{
Expand Down
Loading

0 comments on commit ec57717

Please sign in to comment.