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
2 changes: 1 addition & 1 deletion SySML2.NET.REST.Tests/Integration/LiveServerTestHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public async Task OpenAsync()
}
}

this.Client = new PsmApiClient(this.httpClient, new DeSerializer(), new Serializer(), this.loggerFactory);
this.Client = new PsmApiClient(this.httpClient, new DeSerializer(), new Serializer(), this.loggerFactory, new PsmApiClientOptions { SerializeDerivedProperties = true });
}
}
}
170 changes: 168 additions & 2 deletions SySML2.NET.REST.Tests/PsmApiClientTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ namespace SySML2.NET.REST.Tests

using RichardSzalay.MockHttp;

using SysML2.NET.Core.DTO.Kernel.Functions;
using SysML2.NET.Core.DTO.Root.Namespaces;
using SysML2.NET.PSM;
using SysML2.NET.PSM.DTO;
Expand All @@ -47,6 +48,12 @@ public class PsmApiClientTestFixture

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 ChangeId = Guid.Parse("4b1c7d2e-9f3a-4e6b-8c5d-1a2b3c4d5e6f");

private static readonly KeyValuePair<string, string>[] PreferenceAppliedHeader = [new(PreferenceHeaders.PreferenceApplied, PreferenceHeaders.IncludeDerived)];

private MockHttpMessageHandler mockHttp;

private PsmApiClient client;
Expand All @@ -73,11 +80,26 @@ private static string ReadPayload(string fileName)
return File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, "Data", fileName));
}

private static string CreateFunctionChangePayload()
{
using var rootsDocument = JsonDocument.Parse(ReadPayload("roots.json"));

return $"{{\"@type\":\"DataVersion\",\"@id\":\"{ChangeId}\",\"identity\":{{\"@type\":\"DataIdentity\",\"@id\":\"{FunctionId}\"}},\"payload\":{rootsDocument.RootElement[1].GetRawText()}}}";
}

private static KeyValuePair<string, string>[] CreateLinkHeader(string link)
{
return [new KeyValuePair<string, string>("Link", link)];
}

private PsmApiClient CreateClient(PsmApiClientOptions options)
{
var httpClient = this.mockHttp.ToHttpClient();
httpClient.BaseAddress = BaseAddress;

return new PsmApiClient(httpClient, new DeSerializer(), new Serializer(), options: options);
}

[Test]
public void VerifyConstructor()
{
Expand All @@ -89,6 +111,7 @@ public void VerifyConstructor()
Assert.That(() => new PsmApiClient(httpClient, null, new Serializer()), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), null), Throws.TypeOf<ArgumentNullException>());
Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer()), Throws.Nothing);
Assert.That(() => new PsmApiClient(httpClient, new DeSerializer(), new Serializer(), null, new PsmApiClientOptions { SerializeDerivedProperties = true, RequestDerivedProperties = true }), Throws.Nothing);
}
}

Expand Down Expand Up @@ -235,8 +258,15 @@ public async Task VerifyGetRootsByProjectCommitAsync()
{
Assert.That(roots.Records, Has.Count.EqualTo(2));
Assert.That(roots.Records[0].Id, Is.EqualTo(RootNamespaceId));
Assert.That(roots.Records[1], Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).Null);
}

this.mockHttp.Expect(HttpMethod.Get, rootsUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, ReadPayload("roots.json"));

roots = await this.client.GetRootsByProjectCommitAsync(ProjectId, CommitId);

Assert.That(roots.Records[1], Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll"));

this.mockHttp.Expect(HttpMethod.Get, rootsUri).Respond(HttpStatusCode.NotFound, JsonMediaType, ErrorPayload);

await Assert.ThatAsync(() => this.client.GetRootsByProjectCommitAsync(ProjectId, CommitId),
Expand Down Expand Up @@ -275,19 +305,35 @@ public async Task VerifyGetRelationshipsByProjectCommitRelatedElementAsync()
public async Task VerifyGetElementByProjectCommitIdAsync()
{
var elementUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/elements/{RootNamespaceId}";
var functionUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/elements/{FunctionId}";
var roots = ReadPayload("roots.json");
string functionElement;

using (var rootsDocument = JsonDocument.Parse(roots))
{
this.mockHttp.Expect(HttpMethod.Get, elementUri)
.WithExactQueryString("excludeUsed=false")
.Respond(JsonMediaType, rootsDocument.RootElement[0].GetRawText());

functionElement = rootsDocument.RootElement[1].GetRawText();
}

var element = await this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, RootNamespaceId, false);

Assert.That(element, Is.TypeOf<Namespace>().With.Property(nameof(Namespace.Id)).EqualTo(RootNamespaceId));

this.mockHttp.Expect(HttpMethod.Get, functionUri).Respond(JsonMediaType, functionElement);

element = await this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, FunctionId);

Assert.That(element, Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).Null);

this.mockHttp.Expect(HttpMethod.Get, functionUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, functionElement);

element = await this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, FunctionId);

Assert.That(element, Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll"));

this.mockHttp.Expect(HttpMethod.Get, elementUri).Respond(JsonMediaType, roots);

await Assert.ThatAsync(() => this.client.GetElementByProjectCommitIdAsync(ProjectId, CommitId, RootNamespaceId), Throws.TypeOf<InvalidOperationException>());
Expand All @@ -304,6 +350,68 @@ await Assert.ThatAsync(() => this.client.GetElementByProjectCommitIdAsync(Projec
this.mockHttp.VerifyNoOutstandingExpectation();
}

[Test]
public async Task VerifyGetChangesByProjectCommitAsync()
{
var changesUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/changes";
var changes = $"[{CreateFunctionChangePayload()}]";

this.mockHttp.Expect(HttpMethod.Get, changesUri).Respond(JsonMediaType, changes);

var result = await this.client.GetChangesByProjectCommitAsync(ProjectId, CommitId);

using (Assert.EnterMultipleScope())
{
Assert.That(result.Records, Has.Count.EqualTo(1));
Assert.That(result.Records[0].Id, Is.EqualTo(ChangeId));
Assert.That(result.Records[0].Payload, Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).Null);
}

this.mockHttp.Expect(HttpMethod.Get, changesUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, changes);

result = await this.client.GetChangesByProjectCommitAsync(ProjectId, CommitId);

Assert.That(result.Records[0].Payload, Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll"));

this.mockHttp.Expect(HttpMethod.Get, changesUri).Respond(HttpStatusCode.NotFound, JsonMediaType, ErrorPayload);

await Assert.ThatAsync(() => this.client.GetChangesByProjectCommitAsync(ProjectId, CommitId),
Throws.TypeOf<PsmApiException>().With.Property(nameof(PsmApiException.StatusCode)).EqualTo(HttpStatusCode.NotFound));

this.mockHttp.VerifyNoOutstandingExpectation();
}

[Test]
public async Task VerifyGetChangeByProjectCommitIdAsync()
{
var changeUri = $"{BaseAddress}projects/{ProjectId}/commits/{CommitId}/changes/{ChangeId}";
var change = CreateFunctionChangePayload();

this.mockHttp.Expect(HttpMethod.Get, changeUri).Respond(JsonMediaType, change);

var result = await this.client.GetChangeByProjectCommitIdAsync(ProjectId, CommitId, ChangeId);

using (Assert.EnterMultipleScope())
{
Assert.That(result.Id, Is.EqualTo(ChangeId));
Assert.That(result.Identity.Id, Is.EqualTo(FunctionId));
Assert.That(result.Payload, Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).Null);
}

this.mockHttp.Expect(HttpMethod.Get, changeUri).Respond(HttpStatusCode.OK, PreferenceAppliedHeader, JsonMediaType, change);

result = await this.client.GetChangeByProjectCommitIdAsync(ProjectId, CommitId, ChangeId);

Assert.That(result.Payload, Is.TypeOf<Function>().With.Property(nameof(Function.qualifiedName)).EqualTo("ControlFunctions::forAll"));

this.mockHttp.Expect(HttpMethod.Get, changeUri).Respond(HttpStatusCode.NotFound, JsonMediaType, ErrorPayload);

await Assert.ThatAsync(() => this.client.GetChangeByProjectCommitIdAsync(ProjectId, CommitId, ChangeId),
Throws.TypeOf<PsmApiException>().With.Property(nameof(PsmApiException.StatusCode)).EqualTo(HttpStatusCode.NotFound));

this.mockHttp.VerifyNoOutstandingExpectation();
}

[Test]
public async Task VerifyGetQueryResultsByProjectIdQueryPostAsync()
{
Expand Down Expand Up @@ -374,15 +482,73 @@ await Assert.ThatAsync(() => this.client.PutProjectByIdAsync(ProjectId, projectR
public async Task VerifyMergeAsync()
{
var mergeUri = $"{BaseAddress}projects/{ProjectId}/branches/{BranchId}/merge";
string mergeBody = null;
var hasPreferHeader = false;

this.mockHttp.Expect(HttpMethod.Post, mergeUri)
.WithExactQueryString($"sourceCommitId={CommitId},{OtherCommitId}&description=the%20merge%20description")
.With(request => request.Content.ReadAsStringAsync().GetAwaiter().GetResult().Contains(RootNamespaceId.ToString()))
.With(request =>
{
mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
hasPreferHeader = request.Headers.Contains(PreferenceHeaders.Prefer);
return true;
})
.Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json"));

var mergeCommit = await this.client.MergeAsync(ProjectId, [CommitId, OtherCommitId], BranchId, [new Namespace { Id = RootNamespaceId }], "the merge description");

Assert.That(mergeCommit.Id, Is.EqualTo(CommitId));
using (Assert.EnterMultipleScope())
{
Assert.That(mergeCommit.Id, Is.EqualTo(CommitId));
Assert.That(mergeBody, Does.Contain(RootNamespaceId.ToString()));
Assert.That(mergeBody, Does.Not.Contain("\"qualifiedName\""));
Assert.That(mergeBody, Does.Not.Contain("\"owner\""));
Assert.That(mergeBody, Does.Not.Contain("\"membership\""));
Assert.That(hasPreferHeader, Is.False);
}

var serializingClient = this.CreateClient(new PsmApiClientOptions { SerializeDerivedProperties = true });

this.mockHttp.Expect(HttpMethod.Post, mergeUri)
.WithExactQueryString($"sourceCommitId={CommitId}")
.With(request =>
{
mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
hasPreferHeader = request.Headers.Contains(PreferenceHeaders.Prefer);
return true;
})
.Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json"));

mergeCommit = await serializingClient.MergeAsync(ProjectId, [CommitId], BranchId, [new Namespace { Id = RootNamespaceId }]);

using (Assert.EnterMultipleScope())
{
Assert.That(mergeCommit.Id, Is.EqualTo(CommitId));
Assert.That(mergeBody, Does.Contain("\"qualifiedName\""));
Assert.That(mergeBody, Does.Contain("\"owner\""));
Assert.That(mergeBody, Does.Contain("\"membership\""));
Assert.That(hasPreferHeader, Is.False);
}

var requestingClient = this.CreateClient(new PsmApiClientOptions { RequestDerivedProperties = true });

this.mockHttp.Expect(HttpMethod.Post, mergeUri)
.WithExactQueryString($"sourceCommitId={CommitId}")
.WithHeaders(PreferenceHeaders.Prefer, PreferenceHeaders.IncludeDerived)
.With(request =>
{
mergeBody = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
return true;
})
.Respond(HttpStatusCode.Created, JsonMediaType, ReadPayload("commit.json"));

mergeCommit = await requestingClient.MergeAsync(ProjectId, [CommitId], BranchId, [new Namespace { Id = RootNamespaceId }]);

using (Assert.EnterMultipleScope())
{
Assert.That(mergeCommit.Id, Is.EqualTo(CommitId));
Assert.That(mergeBody, Does.Not.Contain("\"qualifiedName\""));
}

await Assert.ThatAsync(() => this.client.MergeAsync(ProjectId, null, BranchId), Throws.TypeOf<ArgumentNullException>());

Expand Down
19 changes: 18 additions & 1 deletion SySML2.NET.REST.Tests/SessionTestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ namespace SySML2.NET.REST.Tests
using RichardSzalay.MockHttp;

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

Expand Down Expand Up @@ -129,8 +130,24 @@ public async Task VerifyOpen()
Assert.That(this.assembler.Cache, Is.Empty);
}

this.mockHttp.Expect(HttpMethod.Get, "http://localhost/api/projects")
.With(request => !request.Headers.Contains(PreferenceHeaders.Prefer))
.Respond(JsonMediaType, "[]");

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

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

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

await this.session.Open(new Uri("http://localhost/api"), new PsmApiClientOptions { RequestDerivedProperties = true }, CancellationToken.None);

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

this.mockHttp.VerifyNoOutstandingExpectation();
this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(3));
this.httpClientFactory.Verify(factory => factory.CreateClient(nameof(Session)), Times.Exactly(5));
}

[Test]
Expand Down
23 changes: 23 additions & 0 deletions SySML2.NET.REST/ISessionLifecycle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,28 @@ public interface ISessionLifecycle
/// Thrown when <paramref name="baseAddress"/> is not absolute
/// </exception>
Task<PagedResult<Project>> Open(Uri baseAddress, CancellationToken cancellationToken);

/// <summary>
/// Opens a connection to the server with the specified client options, replacing any open connection, and reads the first page of its projects
/// </summary>
/// <param name="baseAddress">
/// The absolute base address of the server
/// </param>
/// <param name="clientOptions">
/// The <see cref="PsmApiClientOptions"/> of the connection, or <c>null</c> to use the defaults
/// </param>
/// <param name="cancellationToken">
/// The <see cref="CancellationToken"/> that cancels the operation
/// </param>
/// <returns>
/// The first page of the projects of the server
/// </returns>
/// <exception cref="ArgumentNullException">
/// Thrown when <paramref name="baseAddress"/> is <c>null</c>
/// </exception>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="baseAddress"/> is not absolute
/// </exception>
Task<PagedResult<Project>> Open(Uri baseAddress, PsmApiClientOptions clientOptions, CancellationToken cancellationToken);
}
}
Loading
Loading