Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created integration test to handlers pull and push #5

Merged
merged 3 commits into from
Dec 31, 2024
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
2 changes: 1 addition & 1 deletion SSync.LiteDB.sln
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{36F96630-08DF-4386-AADB-C8E121988D5B}"
ProjectSection(SolutionItems) = preProject
.github\workflows\publish.yaml = .github\workflows\publish.yaml
readme-ptBR.md = readme-ptBR.md
readme.md = readme.md
.github\workflows\build_and_test.yaml = .github\workflows\build_and_test.yaml
readme.pt-br.md = readme.pt-br.md
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SSync.Server.LitebDB.Integration.Tests", "test\SSync.Server.LitebDB.Integration.Tests\SSync.Server.LitebDB.Integration.Tests.csproj", "{1DF82900-C83A-4813-969C-EFB4E50E4476}"
Expand Down
9 changes: 2 additions & 7 deletions test/SSync.Client.LiteDB.Tests/Sync/PullChanges_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,8 @@ public class PullChanges_Tests
public void SetDatabaseLiteDbNull_SchoudReturnPullChangesExceptions()
{
//arrange
var newUserid = Guid.NewGuid();
var newUserName = $"Cotoso {DateTime.UtcNow}";

var lastPulledAt = DateTime.MinValue;
var lastPulledAt = DateTime.MinValue;
var collectionName = "user";
var now = DateTime.Now;

//act

Expand All @@ -40,7 +36,6 @@ public void LastPulledAtLessZero_ShouldReturnExceptionPullChangesException()

var lastPulledAt = DateTime.MinValue;
var collectionName = "user";
var now = DateTime.Now;

using var database = new LiteDatabase(new MemoryStream());

Expand All @@ -66,7 +61,7 @@ public void InsertAndUpdatedAndDeleteRowsSync_ShouldReturnPullChangesWithSameMet
{
var colUserName = "user";

var users = Enumerable.Range(0, 4).Select(u => new User(Guid.NewGuid())
var users = Enumerable.Range(0, 4).Select(_ => new User(Guid.NewGuid())
{
Name = $"Cotoso {DateTime.UtcNow}"
}).ToArray();
Expand Down
19 changes: 6 additions & 13 deletions test/SSync.Client.LiteDB.Tests/Sync/PushChanges_Tests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using LiteDB;
using SSync.Client.LitebDB.Abstractions.Sync;
using SSync.Client.LitebDB.Exceptions;
using SSync.Client.LitebDB.Extensions;
using SSync.Client.LitebDB.Poco;
using SSync.Client.LitebDB.Sync;

Expand All @@ -14,16 +13,13 @@ public class PushChanges_Tests
public void SetDatabaseLiteDbNull_SchoudReturnPushChangesExceptions()
{
//arrange
var newUserid = Guid.NewGuid();
var newUserName = $"Cotoso {DateTime.UtcNow}";

var now = DateTime.Now;
LiteDatabase? initializationDb = null;

//act

var sync = new Synchronize(null!);
var sync = new Synchronize(initializationDb!);

Action act = () => sync.PushChangesResult(new LitebDB.Poco.SchemaPush<User>());
Action act = () => sync.PushChangesResult(new SchemaPush<User>());

//assert
PushChangeException exception = Assert.Throws<PushChangeException>(act);
Expand All @@ -35,18 +31,15 @@ public void SetDatabaseLiteDbNull_SchoudReturnPushChangesExceptions()
public void SetSchemaChangeNull_SchoudReturnPushChangesExceptions()
{
//arrange
var newUserid = Guid.NewGuid();
var newUserName = $"Cotoso {DateTime.UtcNow}";

var now = DateTime.Now;
SchemaPush<User>? dtoSchema = null;

//act

using var database = new LiteDatabase(new MemoryStream());

var sync = new Synchronize(database);

Action act = () => sync.PushChangesResult((SchemaPush<User>)null!);
Action act = () => sync.PushChangesResult(dtoSchema!);

//assert
ArgumentNullException exception = Assert.Throws<ArgumentNullException>(act);
Expand All @@ -59,7 +52,7 @@ public void InsertAndUpdatedAndDeleteRowsSync_ShouldReturnPushChangesWithSameMet
{
var colUserName = "user";

var users = Enumerable.Range(0, 4).Select(u => new User(Guid.NewGuid())
var users = Enumerable.Range(0, 4).Select(_ => new User(Guid.NewGuid())
{
Name = $"Cotoso {DateTime.UtcNow}"
}).ToArray();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using LiteDB;
using SSync.Client.LitebDB.Abstractions.Sync;
using SSync.Client.LitebDB.Extensions;
using SSync.Client.LitebDB.Sync;
using static SSync.Client.LiteDB.Tests.Sync.PullChanges_Tests;

Expand Down Expand Up @@ -120,10 +119,6 @@ public void UpdateCollectionSync_ShouldReturnStatusCreated()

//assert

var changes = sync.PullChangesResult<User>(DateTime.MinValue, collectionName);

var userUpdated = changes.Changes.Updated.FirstOrDefault(u => u.Id == newUserid);

Assert.True(user.Status == StatusSync.UPDATED);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using SSync.Server.LiteDB.PlayGround.Data;
using Testcontainers.PostgreSql;

Expand All @@ -13,7 +12,7 @@
{
private readonly PostgreSqlContainer _postgreSqlContainer;

public IntegrationFixture()

Check warning on line 15 in test/SSync.Server.LitebDB.Integration.Tests/MockServerApp/IntegrationFixture.cs

View workflow job for this annotation

GitHub Actions / Build and Tests SSync Client and Server

Non-nullable property 'App' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 15 in test/SSync.Server.LitebDB.Integration.Tests/MockServerApp/IntegrationFixture.cs

View workflow job for this annotation

GitHub Actions / Build and Tests SSync Client and Server

Non-nullable property 'Client' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
{
_postgreSqlContainer = new PostgreSqlBuilder()
.WithDatabase("ssync-litedb-db-test")
Expand Down Expand Up @@ -77,7 +76,7 @@
[Collection(nameof(IntegrationFixtureCollection))]
public class IntegrationTest : IAsyncLifetime
{
public IntegrationTest(IntegrationFixture integrationFixture )

Check warning on line 79 in test/SSync.Server.LitebDB.Integration.Tests/MockServerApp/IntegrationFixture.cs

View workflow job for this annotation

GitHub Actions / Build and Tests SSync Client and Server

Non-nullable property 'Scope' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.

Check warning on line 79 in test/SSync.Server.LitebDB.Integration.Tests/MockServerApp/IntegrationFixture.cs

View workflow job for this annotation

GitHub Actions / Build and Tests SSync Client and Server

Non-nullable property 'DbContext' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
{
IntegrationFixture = integrationFixture;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using SSync.Server.LitebDB.Poco;
using SSync.Server.LiteDB.PlayGround.Sync.Dto;

namespace SSync.Server.LitebDB.Integration.Tests.MockServerApp.Sync.Handlers
{
/// <summary>
/// Create test sync pull request handlers
/// </summary>
public class PullRequest_Test : IntegrationTest
{
private readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

public PullRequest_Test(IntegrationFixture integrationFixture) : base(integrationFixture)
{
ArgumentNullException.ThrowIfNull(integrationFixture.Client);
}

[Fact]
public async Task SetTimestamp_To_PullAllChanges_Should_Return_Only_Created_Values()
{
var createResult = await Client.GetAsync("/create");

Assert.True(createResult.IsSuccessStatusCode);

var pullResult = await Client.GetAsync($"/pull?Time=0&Colletions=User&Timestamp={DateTime.MinValue:o}", CancellationToken.None);
Assert.True(pullResult.IsSuccessStatusCode);

var content = await pullResult.Content.ReadAsStringAsync();

var data = JsonSerializer.Deserialize<JsonArray>(content);

Assert.True(data!.Any());

var usersChanges = data!.FirstOrDefault().Deserialize<SchemaPush<UserSync>>(_jsonSerializerOptions);

Assert.NotNull(usersChanges);
Assert.True(usersChanges.HasCreated);
Assert.False(usersChanges.HasUpdated);
Assert.False(usersChanges.HasDeleted);
}

[Fact]
public async Task Set_Current_Timestamp_To_PullChanges_Should_Return_Value_From_Current_DateTime()
{
var currentTime = DateTime.UtcNow;

var createResult = await Client.GetAsync("/create");

Assert.True(createResult.IsSuccessStatusCode);

var pullResult = await Client.GetAsync($"/pull?Time=0&Colletions=User&Timestamp={currentTime:o}", CancellationToken.None);
Assert.True(pullResult.IsSuccessStatusCode);

var content = await pullResult.Content.ReadAsStringAsync();

var data = JsonSerializer.Deserialize<JsonArray>(content);

Assert.True(data!.Any());

var usersChanges = data!.FirstOrDefault().Deserialize<SchemaPush<UserSync>>(_jsonSerializerOptions);

Assert.NotNull(usersChanges);
Assert.True(usersChanges.HasChanges);
Assert.True(usersChanges.HasCreated);
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using SSync.Server.LitebDB.Poco;
using SSync.Server.LiteDB.PlayGround.Sync.Dto;

namespace SSync.Server.LitebDB.Integration.Tests.MockServerApp.Sync.Handlers;

/// <summary>
/// Create test sync push request handlers
/// </summary>
public class PushRequest_Test : IntegrationTest
{
public PushRequest_Test(IntegrationFixture integrationFixture) : base(integrationFixture)
{
}

[Fact]
public async Task Create_New_Users_From_Json_Should_Return_Created_Users_Database()
{
var jsonChangesFromClient = """
[
{
"collection": "User",
"timestamp": "2024-12-31T16:58:51.5566008Z",
"changes": {
"created": [
{
"name": " Cotoso 589970329",
"id": "1851d7ed-ea2b-4b17-8e77-ab6fb2cb8f81",
"createdAt": "2024-12-31T16:58:51.172117",
"updatedAt": "2024-12-31T16:58:51.172117",
"deletedAt": null
}
],
"updated": [],
"deleted": []
}
}
]
""";

var content = new StringContent(jsonChangesFromClient, Encoding.UTF8, "application/json");

var pullResult =
await Client.PostAsync($"/push?Time=0&Colletions=User&Timestamp={DateTime.MinValue:o}", content);
Assert.True(pullResult.IsSuccessStatusCode);

var user = DbContext.User.FirstOrDefault(u => u.Id == Guid.Parse("1851d7ed-ea2b-4b17-8e77-ab6fb2cb8f81"));

Assert.NotNull(user);
}


[Fact]
public async Task Update_Users_From_Json_Should_Return_Updated_Users_Database()
{
var createResult = await Client.GetAsync("/create");

Assert.True(createResult.IsSuccessStatusCode);

var user = DbContext.User.FirstOrDefault()!;

var currentTime = DateTime.UtcNow;
user.Name = "Cotoso updated";
user.SetUpdatedAt(currentTime);

DbContext.User.Update(user);
await DbContext.SaveChangesAsync();

var changes = new List<SchemaPush<UserSync>>
{
Capacity = 0
};

var updateUserSchemaSync = new SchemaPush<UserSync>
{
Collection = "User",
Timestamp = currentTime,
Changes = new SchemaPush<UserSync>.Change()
{
Created = [],
Updated =
[
new UserSync(user.Id)
{
Name = user.Name,
CreatedAt = user.CreatedAt,
UpdatedAt = user.UpdatedAt
}
],
Deleted = []
}
};

changes.Add(updateUserSchemaSync);


var serializeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};

var jsonChangesFromClient = JsonSerializer.Serialize(changes, serializeOptions);

var content = new StringContent(jsonChangesFromClient, Encoding.UTF8, "application/json");

var pullResult =
await Client.PostAsync($"/push?Time=0&Colletions=User&Timestamp={DateTime.MinValue:o}", content);
Assert.True(pullResult.IsSuccessStatusCode);

DbContext.ChangeTracker.Clear();

var userUpdate = DbContext.User.FirstOrDefault(u => u.Id == user.Id)!;

Assert.NotEqual(userUpdate.CreatedAt, userUpdate.UpdatedAt);
}

[Fact]
public async Task Delete_Users_From_Json_Should_Return_Delete_Users_Database()
{
var createResult = await Client.GetAsync("/create");

Assert.True(createResult.IsSuccessStatusCode);

var user = DbContext.User.FirstOrDefault()!;

var currentTime = DateTime.UtcNow;
user.SetDeletedAt(currentTime);

DbContext.User.Update(user);
await DbContext.SaveChangesAsync();

var changes = new List<SchemaPush<UserSync>>
{
Capacity = 0
};

var deleteUserSchemaSync = new SchemaPush<UserSync>
{
Collection = "User",
Timestamp = currentTime,
Changes = new SchemaPush<UserSync>.Change()
{
Created = [],
Updated = [],
Deleted = [user.Id]
}
};

changes.Add(deleteUserSchemaSync);


var serializeOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};

var jsonChangesFromClient = JsonSerializer.Serialize(changes, serializeOptions);

var content = new StringContent(jsonChangesFromClient, Encoding.UTF8, "application/json");

var pullResult =
await Client.PostAsync($"/push?Time=0&Colletions=User&Timestamp={DateTime.MinValue:o}", content);
Assert.True(pullResult.IsSuccessStatusCode);

DbContext.ChangeTracker.Clear();

var userDeleted = DbContext.User.FirstOrDefault(u => u.Id == user.Id)!;

Assert.NotNull(userDeleted.DeletedAt);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,4 @@
<ProjectReference Include="..\..\src\SSync.Server.LiteDB.PlayGround\SSync.Server.LiteDB.PlayGround.csproj" />
</ItemGroup>

<ItemGroup>
<Folder Include="MockServerApp\Sync\Handlers\Pull\" />
</ItemGroup>

</Project>
Loading