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
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,32 @@ namespace SySML2.NET.REST.Tests.Integration
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Extensions.DependencyInjection;

using NUnit.Framework;
using NUnit.Framework.Constraints;

using SysML2.NET.Core.DTO.Kernel.Packages;
using SysML2.NET.Core.DTO.Root.Namespaces;
using SysML2.NET.Core.DTO.Systems.Parts;
using SysML2.NET.Dal;
using SysML2.NET.PSM;
using SysML2.NET.PSM.DTO;
using SysML2.NET.PSM.Enumerations;
using SysML2.NET.REST.Exceptions;
using SysML2.NET.Serializer.Json;

[TestFixture]
[Category("Integration")]
public class PsmApiClientIntegrationTestFixture
{
private const int PageSize = 2;

private const string BaseAddressVariable = "SYSML2_API_BASE_ADDRESS";

private const int DatatypePageSize = 100;

private const string ProjectNamePrefix = "SysML2.NET-it-";
Expand All @@ -46,6 +53,8 @@ public class PsmApiClientIntegrationTestFixture

private static readonly string[] SelectedProperties = ["@id", "@type"];

private static readonly Guid[] SeedElementIds = [DefaultSeedModel.PackageId, DefaultSeedModel.MembershipId, DefaultSeedModel.PartDefinitionId];

private readonly List<Guid> createdProjectIds = [];

private LiveServerTestHost host;
Expand Down Expand Up @@ -519,6 +528,67 @@ public async Task VerifyGetTagsByProjectAsync()
await Assert.ThatAsync(() => this.client.GetTagsByProjectAsync(UnknownId), ThrowsNotFound());
}

[Test]
public async Task VerifyLoadBranchHead()
{
await using var services = CreateSessionServices();
await using var scope = services.CreateAsyncScope();
var session = await OpenSessionAsync(scope.ServiceProvider);

await session.LoadBranchHead(this.projectId, this.defaultBranchId, CancellationToken.None);

Assert.That(session.Assembler.Cache.Keys, Is.EquivalentTo(SeedElementIds));

using (Assert.EnterMultipleScope())
{
Assert.That(session.CurrentCommit, Is.EqualTo((this.projectId, this.seedCommitId)));
Assert.That(session.Assembler.Cache[DefaultSeedModel.PartDefinitionId].Value.DeclaredName, Is.EqualTo(DefaultSeedModel.PartDefinitionName));
await Assert.ThatAsync(() => session.LoadBranchHead(this.projectId, UnknownId, CancellationToken.None), ThrowsNotFound());
Assert.That(session.CurrentCommit, Is.EqualTo((this.projectId, this.seedCommitId)));
}
}

[Test]
public async Task VerifyLoadCommit()
{
await using var services = CreateSessionServices();
await using var scope = services.CreateAsyncScope();
var session = await OpenSessionAsync(scope.ServiceProvider);

await session.LoadCommit(this.projectId, this.seedCommitId, CancellationToken.None);

Assert.That(session.Assembler.Cache.Keys, Is.EquivalentTo(SeedElementIds));

var package = session.Assembler.Cache[DefaultSeedModel.PackageId].Value;
var membership = (SysML2.NET.Core.POCO.Root.Elements.IRelationship)session.Assembler.Cache[DefaultSeedModel.MembershipId].Value;
var partDefinition = session.Assembler.Cache[DefaultSeedModel.PartDefinitionId].Value;

using (Assert.EnterMultipleScope())
{
Assert.That(session.CurrentCommit, Is.EqualTo((this.projectId, this.seedCommitId)));
Assert.That(package.OwnedRelationship, Is.EquivalentTo([membership]));
Assert.That(membership.OwnedRelatedElement, Is.EquivalentTo([partDefinition]));
Assert.That(partDefinition.DeclaredName, Is.EqualTo(DefaultSeedModel.PartDefinitionName));
}

var branch = await this.client.PostBranchByProjectAsync(this.projectId, new BranchRequest { Name = "load-commit", Head = this.seedCommitId });
var renameCommit = await this.client.PostCommitByProjectAsync(this.projectId, DefaultSeedModel.CreateRenameRequest("Truck"), branch.Id);

await session.LoadCommit(this.projectId, renameCommit.Id, CancellationToken.None);

Assert.That(session.Assembler.Cache.Keys, Is.EquivalentTo(SeedElementIds));

using (Assert.EnterMultipleScope())
{
Assert.That(session.CurrentCommit, Is.EqualTo((this.projectId, renameCommit.Id)));
Assert.That(session.Assembler.Cache[DefaultSeedModel.PartDefinitionId].Value, Is.SameAs(partDefinition));
Assert.That(partDefinition.DeclaredName, Is.EqualTo("Truck"));
await Assert.ThatAsync(() => session.LoadCommit(this.projectId, UnknownId, CancellationToken.None), ThrowsNotFound());
Assert.That(session.CurrentCommit, Is.EqualTo((this.projectId, renameCommit.Id)));
Assert.That(session.Assembler.Cache.Keys, Is.EquivalentTo(SeedElementIds));
}
}

[Test]
public async Task VerifyMergeAsync()
{
Expand Down Expand Up @@ -715,6 +785,17 @@ private static QueryRequest CreatePartDefinitionQuery()
};
}

private static ServiceProvider CreateSessionServices()
{
return new ServiceCollection()
.AddScoped<IAssembler, Assembler>()
.AddScoped<IDeSerializer, DeSerializer>()
.AddScoped<ISerializer, Serializer>()
.AddScoped<ISession, Session>()
.AddHttpClient(nameof(Session), httpClient => httpClient.Timeout = TimeSpan.FromSeconds(180)).Services
.BuildServiceProvider();
}

private static async Task<T> GetOrNullWhenNotFoundAsync<T>(Func<Task<T>> read) where T : class
{
try
Expand All @@ -727,6 +808,14 @@ private static async Task<T> GetOrNullWhenNotFoundAsync<T>(Func<Task<T>> read) w
}
}

private static async Task<ISession> OpenSessionAsync(IServiceProvider services)
{
var session = services.GetRequiredService<ISession>();
await session.Open(new Uri(Environment.GetEnvironmentVariable(BaseAddressVariable)), CancellationToken.None);

return session;
}

private static async Task<T> SupportedAsync<T>(Func<Task<T>> operation)
{
try
Expand Down
192 changes: 182 additions & 10 deletions SySML2.NET.REST.Tests/SessionTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@
namespace SySML2.NET.REST.Tests
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

Expand All @@ -21,6 +25,7 @@ namespace SySML2.NET.REST.Tests

using RichardSzalay.MockHttp;

using SysML2.NET.Dal;
using SysML2.NET.REST.Exceptions;
using SysML2.NET.Serializer.Json;

Expand All @@ -29,10 +34,32 @@ public class SessionTestFixture
{
private const string JsonMediaType = "application/json";

private static readonly Guid ProjectId = Guid.Parse("000e9890-6935-43e6-a5d7-5d7cac601f4c");

private static readonly Guid BranchId = Guid.Parse("c294a463-6c9c-47a8-b592-01252c5ab2a7");

private static readonly Guid EmptyBranchId = Guid.Parse("5b1c3e7a-2f4d-4c8e-9a6b-1d2e3f4a5b6c");

private static readonly Guid CommitId = Guid.Parse("6d7ad9fd-6520-4ff2-885b-8c5c129e6c27");

private static readonly Guid OtherCommitId = Guid.Parse("2f1a0e1c-6b2a-4d5e-9c3f-8a7b6d5e4c3b");

private static readonly Guid LoopingCommitId = Guid.Parse("9c8b7a6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d");

private static readonly Guid RootNamespaceId = Guid.Parse("864d5403-c87b-4679-9d3a-b09c7fde1dd9");

private static readonly Guid FunctionId = Guid.Parse("761f87bf-e06e-55f7-8830-ebcc3f619e2d");

private static readonly Guid[] RootIds = [RootNamespaceId, FunctionId];

private static readonly string ElementsUri = $"http://localhost/api/projects/{ProjectId}/commits/";

private MockHttpMessageHandler mockHttp;

private Mock<IHttpClientFactory> httpClientFactory;

private Assembler assembler;

private Session session;

[SetUp]
Expand All @@ -42,7 +69,8 @@ public void SetUp()
this.httpClientFactory = new Mock<IHttpClientFactory>();
this.httpClientFactory.Setup(factory => factory.CreateClient(nameof(Session))).Returns(() => this.mockHttp.ToHttpClient());

this.session = new Session(this.httpClientFactory.Object, new DeSerializer(), new Serializer());
this.assembler = new Assembler();
this.session = new Session(this.httpClientFactory.Object, new DeSerializer(), new Serializer(), this.assembler);
}

[TearDown]
Expand All @@ -56,18 +84,23 @@ public void VerifyConstructor()
{
using (Assert.EnterMultipleScope())
{
Assert.That(() => new Session(null, new DeSerializer(), new Serializer()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new Session(this.httpClientFactory.Object, null, new Serializer()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new Session(this.httpClientFactory.Object, new DeSerializer(), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new Session(null, new DeSerializer(), new Serializer(), this.assembler), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new Session(this.httpClientFactory.Object, null, new Serializer(), this.assembler), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new Session(this.httpClientFactory.Object, new DeSerializer(), null, this.assembler), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new Session(this.httpClientFactory.Object, new DeSerializer(), new Serializer(), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(this.session.Assembler, Is.SameAs(this.assembler));
Assert.That(this.session.Client, Is.Null);
}
}

[Test]
public async Task VerifyOpen()
{
await Assert.ThatAsync(() => this.session.Open(null, CancellationToken.None), Throws.TypeOf<ArgumentNullException>());
await Assert.ThatAsync(() => this.session.Open(new Uri("api", UriKind.Relative), CancellationToken.None), Throws.TypeOf<ArgumentException>());
using (Assert.EnterMultipleScope())
{
await Assert.ThatAsync(() => this.session.Open(null, CancellationToken.None), Throws.TypeOf<ArgumentNullException>());
await Assert.ThatAsync(() => this.session.Open(new Uri("api", UriKind.Relative), CancellationToken.None), Throws.TypeOf<ArgumentException>());
}

this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").Respond(JsonMediaType, "[]");

Expand All @@ -89,9 +122,12 @@ public async Task VerifyOpen()

this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").Respond(HttpStatusCode.InternalServerError);

await Assert.ThatAsync(() => this.session.Open(new Uri("http://localhost/api/"), CancellationToken.None), Throws.TypeOf<PsmApiException>());

Assert.That(this.session.Client, Is.Null);
using (Assert.EnterMultipleScope())
{
await Assert.ThatAsync(() => this.session.Open(new Uri("http://localhost/api/"), CancellationToken.None), Throws.TypeOf<PsmApiException>());
Assert.That(this.session.Client, Is.Null);
Assert.That(this.assembler.Cache, Is.Empty);
}

this.mockHttp.VerifyNoOutstandingExpectation();
this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(3));
Expand All @@ -110,9 +146,145 @@ public async Task VerifyClose()

Assert.That(this.session.Client, Is.Not.Null);

this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{CommitId}/elements").Respond(JsonMediaType, ReadPayload("roots.json"));
await this.session.LoadCommit(ProjectId, CommitId, CancellationToken.None);

using (Assert.EnterMultipleScope())
{
Assert.That(this.session.CurrentCommit, Is.EqualTo((ProjectId, CommitId)));
Assert.That(this.assembler.Cache.Keys, Is.EquivalentTo(RootIds));
}

this.session.Close();

Assert.That(this.session.Client, Is.Null);
using (Assert.EnterMultipleScope())
{
Assert.That(this.session.Client, Is.Null);
Assert.That(this.session.CurrentCommit, Is.Null);
Assert.That(this.assembler.Cache, Is.Empty);
}

this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").Respond(JsonMediaType, "[]");
this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{CommitId}/elements").Respond(JsonMediaType, ReadPayload("roots.json"));

await this.session.Open(new Uri("http://localhost/api/"), CancellationToken.None);
await this.session.LoadCommit(ProjectId, CommitId, CancellationToken.None);

Assert.That(this.assembler.Cache.Keys, Is.EquivalentTo(RootIds));

this.mockHttp.VerifyNoOutstandingExpectation();
}

[Test]
public async Task VerifyLoadCommit()
{
await Assert.ThatAsync(() => this.session.LoadCommit(ProjectId, CommitId, CancellationToken.None), Throws.TypeOf<InvalidOperationException>().With.Message.Contains("closed"));

using var roots = JsonDocument.Parse(ReadPayload("roots.json"));
var namespaceElement = roots.RootElement[0].GetRawText();
var functionElement = roots.RootElement[1].GetRawText();

this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").Respond(JsonMediaType, "[]");
await this.session.Open(new Uri("http://localhost/api/"), CancellationToken.None);

this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{CommitId}/elements").WithExactQueryString(string.Empty)
.Respond(HttpStatusCode.OK, [new KeyValuePair<string, string>("Link", $"<{ElementsUri}{CommitId}/elements?page[after]=second>; rel=\"next\"")], JsonMediaType, $"[{namespaceElement}]");
this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{CommitId}/elements").WithExactQueryString("page[after]=second").Respond(JsonMediaType, $"[{functionElement}]");

await this.session.LoadCommit(ProjectId, CommitId, CancellationToken.None);

using (Assert.EnterMultipleScope())
{
Assert.That(this.assembler.Cache.Keys, Is.EquivalentTo(RootIds));
Assert.That(this.session.CurrentCommit, Is.EqualTo((ProjectId, CommitId)));
}

var function = this.assembler.Cache[FunctionId].Value;

await this.session.LoadCommit(ProjectId, CommitId, CancellationToken.None);

Assert.That(this.assembler.Cache[FunctionId].Value, Is.SameAs(function));

this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{OtherCommitId}/elements").Respond(JsonMediaType, $"[{functionElement}]");

await this.session.LoadCommit(ProjectId, OtherCommitId, CancellationToken.None);

using (Assert.EnterMultipleScope())
{
Assert.That(this.assembler.Cache.Keys, Is.EquivalentTo([FunctionId]));
Assert.That(this.assembler.Cache[FunctionId].Value, Is.SameAs(function));
Assert.That(this.session.CurrentCommit, Is.EqualTo((ProjectId, OtherCommitId)));
}

var repeatingLink = new KeyValuePair<string, string>("Link", $"<{ElementsUri}{LoopingCommitId}/elements?page[after]=again>; rel=\"next\"");
this.mockHttp.When(HttpMethod.Get, $"{ElementsUri}{LoopingCommitId}/elements").Respond(HttpStatusCode.OK, [repeatingLink], JsonMediaType, "[]");

using (Assert.EnterMultipleScope())
{
await Assert.ThatAsync(() => this.session.LoadCommit(ProjectId, LoopingCommitId, CancellationToken.None), Throws.TypeOf<InvalidOperationException>().With.Message.Contains("already returned"));
Assert.That(this.session.CurrentCommit, Is.EqualTo((ProjectId, OtherCommitId)));
}

this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{CommitId}/elements").Respond(_ =>
{
this.session.Close();
return JsonResponse(ReadPayload("roots.json"));
});

await this.session.LoadCommit(ProjectId, CommitId, CancellationToken.None);

using (Assert.EnterMultipleScope())
{
Assert.That(this.assembler.Cache, Is.Empty);
Assert.That(this.session.CurrentCommit, Is.Null);
}

this.mockHttp.VerifyNoOutstandingExpectation();
}

[Test]
public async Task VerifyLoadBranchHead()
{
await Assert.ThatAsync(() => this.session.LoadBranchHead(ProjectId, BranchId, CancellationToken.None), Throws.TypeOf<InvalidOperationException>().With.Message.Contains("closed"));

this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects").Respond(JsonMediaType, "[]");
await this.session.Open(new Uri("http://localhost/api/"), CancellationToken.None);

this.mockHttp.Expect(HttpMethod.Get, $"http://localhost/api/projects/{ProjectId}/branches/{BranchId}").Respond(JsonMediaType, ReadPayload("branch.json"));
this.mockHttp.Expect(HttpMethod.Get, $"{ElementsUri}{CommitId}/elements").Respond(JsonMediaType, ReadPayload("roots.json"));
this.mockHttp.Expect(HttpMethod.Get, $"http://localhost/api/projects/{ProjectId}/branches/{BranchId}").Respond(JsonMediaType, ReadPayload("branch.json"));

await this.session.LoadBranchHead(ProjectId, BranchId, CancellationToken.None);
await this.session.LoadBranchHead(ProjectId, BranchId, CancellationToken.None);

using (Assert.EnterMultipleScope())
{
Assert.That(this.assembler.Cache.Keys, Is.EquivalentTo(RootIds));
Assert.That(this.session.CurrentCommit, Is.EqualTo((ProjectId, CommitId)));
}

this.mockHttp.Expect(HttpMethod.Get, $"http://localhost/api/projects/{ProjectId}/branches/{EmptyBranchId}")
.Respond(JsonMediaType, $"{{\"@id\":\"{EmptyBranchId}\",\"@type\":\"Branch\",\"created\":\"2023-03-13T17:53:50.188295-04:00\",\"head\":null,\"name\":\"empty\",\"owningProject\":{{\"@id\":\"{ProjectId}\"}},\"referencedCommit\":null}}");

await this.session.LoadBranchHead(ProjectId, EmptyBranchId, CancellationToken.None);

using (Assert.EnterMultipleScope())
{
Assert.That(this.assembler.Cache, Is.Empty);
Assert.That(this.session.CurrentCommit, Is.Null);
}

this.mockHttp.VerifyNoOutstandingExpectation();
}

private static HttpResponseMessage JsonResponse(string content)
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(content, Encoding.UTF8, JsonMediaType) };
}

private static string ReadPayload(string fileName)
{
return File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", fileName));
}
}
}
Loading
Loading