Skip to content

Commit

Permalink
tests: add tests for policyhub bl
Browse files Browse the repository at this point in the history
Refs: CPLP-3362
  • Loading branch information
Phil91 committed Dec 2, 2023
1 parent 32438de commit d99e652
Show file tree
Hide file tree
Showing 23 changed files with 450 additions and 312 deletions.
1 change: 1 addition & 0 deletions DEPENDENCIES
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ nuget/nuget/-/FluentAssertions/6.11.0, Apache-2.0 AND MIT, approved, #10061
nuget/nuget/-/Flurl.Signed/3.0.6, MIT, approved, #3501
nuget/nuget/-/Humanizer.Core/2.14.1, MIT, approved, #10060
nuget/nuget/-/Mono.TextTemplating/2.2.1, MIT, approved, clearlydefined
nuget/nuget/-/Newtonsoft.Json/13.0.1, MIT AND BSD-3-Clause, approved, #3266
nuget/nuget/-/Newtonsoft.Json/13.0.3, MIT AND BSD-3-Clause, approved, #3266
nuget/nuget/-/Npgsql.EntityFrameworkCore.PostgreSQL/7.0.11, PostgreSQL AND MIT AND Apache-2.0, approved, #10081
nuget/nuget/-/Npgsql/7.0.6, PostgreSQL, approved, #10062
Expand Down
7 changes: 7 additions & 0 deletions src/PolicyHub.sln
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolicyHub.DbAccess.Tests",
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolicyHub.Service.Tests", "..\tests\hub\PolicyHub.Service.Tests\PolicyHub.Service.Tests.csproj", "{A337EA35-B303-4F1B-9A83-5205E2CBA69D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PolicyHub.Entities.Tests", "..\tests\database\PolicyHub.Entities.Tests\PolicyHub.Entities.Tests.csproj", "{1F4F15B3-C3D6-4030-9822-62D72B6DA1C9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -48,6 +50,10 @@ Global
{A337EA35-B303-4F1B-9A83-5205E2CBA69D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A337EA35-B303-4F1B-9A83-5205E2CBA69D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A337EA35-B303-4F1B-9A83-5205E2CBA69D}.Release|Any CPU.Build.0 = Release|Any CPU
{1F4F15B3-C3D6-4030-9822-62D72B6DA1C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1F4F15B3-C3D6-4030-9822-62D72B6DA1C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1F4F15B3-C3D6-4030-9822-62D72B6DA1C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1F4F15B3-C3D6-4030-9822-62D72B6DA1C9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{92B16AED-3229-4C46-8498-11D33E5C7F69} = {D30D713C-43E8-488F-BFBB-FD610E77ACA3}
Expand All @@ -56,5 +62,6 @@ Global
{F5BED39D-6419-49AD-A5E0-FAB88723285C} = {6EB9F0CF-3A57-42AA-BF74-AADCF8815F90}
{F1551715-BECA-45B2-A71B-CAB60F2D35FE} = {9C9DA872-893E-48BA-9DD5-025D477F6EC3}
{A337EA35-B303-4F1B-9A83-5205E2CBA69D} = {9C9DA872-893E-48BA-9DD5-025D477F6EC3}
{1F4F15B3-C3D6-4030-9822-62D72B6DA1C9} = {9C9DA872-893E-48BA-9DD5-025D477F6EC3}
EndGlobalSection
EndGlobal
16 changes: 0 additions & 16 deletions src/database/PolicyHub.DbAccess/HubRepositories.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

using Microsoft.EntityFrameworkCore;
using Org.Eclipse.TractusX.PolicyHub.DbAccess.Repositories;
using Org.Eclipse.TractusX.PolicyHub.Entities;
using Org.Eclipse.TractusX.Portal.Backend.Framework.ErrorHandling.Library;
using System.Collections.Immutable;

namespace Org.Eclipse.TractusX.PolicyHub.DbAccess;
Expand Down Expand Up @@ -49,18 +47,4 @@ public RepositoryType GetInstance<RepositoryType>()

return (RepositoryType)(repository ?? throw new ArgumentException($"unexpected type {typeof(RepositoryType).Name}", nameof(RepositoryType)));
}

public Task<int> SaveAsync()
{
try
{
return _dbContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException e)
{
throw new ConflictException("while processing a concurrent update was saved to the database (reason could also be data to be deleted is no longer existing)", e);
}
}

public void Clear() => _dbContext.ChangeTracker.Clear();
}
4 changes: 0 additions & 4 deletions src/database/PolicyHub.DbAccess/IHubRepositories.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,4 @@ namespace Org.Eclipse.TractusX.PolicyHub.DbAccess;
public interface IHubRepositories
{
public T GetInstance<T>();

public Task<int> SaveAsync();

void Clear();
}
21 changes: 4 additions & 17 deletions src/database/PolicyHub.Entities/PolicyHubContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ namespace Org.Eclipse.TractusX.PolicyHub.Entities;

public class PolicyHubContext : DbContext
{
public PolicyHubContext()
{
}

public PolicyHubContext(DbContextOptions<PolicyHubContext> options)
: base(options)
{
Expand Down Expand Up @@ -94,23 +98,6 @@ protected override void OnModelCreating(ModelBuilder modelBuilder)
x.HasKey(e => new { e.PolicyId, e.UseCaseId });
});
entity.HasMany(p => p.UseCases)
.WithMany(pt => pt.Policies)
.UsingEntity<PolicyAssignedUseCases>(p => p
.HasOne(x => x.UseCase)
.WithMany()
.HasForeignKey(x => x.UseCaseId)
.OnDelete(DeleteBehavior.ClientSetNull),
p => p
.HasOne(x => x.Policy)
.WithMany()
.HasForeignKey(x => x.PolicyId)
.OnDelete(DeleteBehavior.ClientSetNull),
x =>
{
x.HasKey(e => new { e.PolicyId, e.UseCaseId });
});
entity.HasOne(p => p.AttributeKey)
.WithMany(pt => pt.Policies)
.HasForeignKey(p => p.AttributeKeyId)
Expand Down
2 changes: 1 addition & 1 deletion src/database/PolicyHub.Migrations/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
.AddDbContext<PolicyHubContext>(o =>
o.UseNpgsql(hostContext.Configuration.GetConnectionString("PolicyHubDb"),
x => x.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name)
.MigrationsHistoryTable("__efmigrations_history_hub")))
.MigrationsHistoryTable("__efmigrations_history_hub", "public")))
.AddDatabaseInitializer<PolicyHubContext>(hostContext.Configuration.GetSection("Seeding"));
})
.AddLogging()
Expand Down
10 changes: 5 additions & 5 deletions src/database/PolicyHub.Migrations/Seeder/BatchInsertSeeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,21 +70,21 @@ public async Task ExecuteAsync(CancellationToken cancellationToken)

private async Task SeedTable<T>(string fileName, Func<T, object> keySelector, CancellationToken cancellationToken) where T : class
{
_logger.LogInformation("Start seeding {Filename}", fileName);
_logger.LogDebug("Start seeding {Filename}", fileName);
var additionalEnvironments = _settings.TestDataEnvironments ?? Enumerable.Empty<string>();
var data = await SeederHelper.GetSeedData<T>(_logger, fileName, _settings.DataPaths, cancellationToken, additionalEnvironments.ToArray()).ConfigureAwait(false);
_logger.LogInformation("Found {ElementCount} data", data.Count);
_logger.LogDebug("Found {ElementCount} data", data.Count);
if (data.Any())
{
var typeName = typeof(T).Name;
_logger.LogInformation("Started to Seed {TableName}", typeName);
_logger.LogDebug("Started to Seed {TableName}", typeName);
data = data.GroupJoin(_context.Set<T>(), keySelector, keySelector, (d, dbEntry) => new { d, dbEntry })
.SelectMany(t => t.dbEntry.DefaultIfEmpty(), (t, x) => new { t, x })
.Where(t => t.x == null)
.Select(t => t.t.d).ToList();
_logger.LogInformation("Seeding {DataCount} {TableName}", data.Count, typeName);
_logger.LogDebug("Seeding {DataCount} {TableName}", data.Count, typeName);
await _context.Set<T>().AddRangeAsync(data, cancellationToken).ConfigureAwait(false);
_logger.LogInformation("Seeded {TableName}", typeName);
_logger.LogDebug("Seeded {TableName}", typeName);
}
}
}
9 changes: 5 additions & 4 deletions src/database/PolicyHub.Migrations/Seeder/BatchUpdateSeeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,10 @@ await SeedTable<PolicyAttribute>(

private async Task SeedTable<T>(string fileName, Func<T, object> keySelector, Func<(T dataEntity, T dbEntity), bool> whereClause, Action<T, T> updateEntries, CancellationToken cancellationToken) where T : class
{
_logger.LogInformation("Start seeding {Filename}", fileName);
_logger.LogDebug("Start seeding {Filename}", fileName);
var additionalEnvironments = _settings.TestDataEnvironments ?? Enumerable.Empty<string>();
var data = await SeederHelper.GetSeedData<T>(_logger, fileName, _settings.DataPaths, cancellationToken, additionalEnvironments.ToArray()).ConfigureAwait(false);
_logger.LogInformation("Found {ElementCount} data", data.Count);
_logger.LogDebug("Found {ElementCount} data", data.Count);
if (data.Any())
{
var typeName = typeof(T).Name;
Expand All @@ -78,12 +78,13 @@ private async Task SeedTable<T>(string fileName, Func<T, object> keySelector, Fu
.ToList();
if (entriesForUpdate.Any())
{
_logger.LogInformation("Started to Update {EntryCount} entries of {TableName}", entriesForUpdate.Count, typeName);
_logger.LogDebug("Started to Update {EntryCount} entries of {TableName}", entriesForUpdate.Count, typeName);
foreach (var entry in entriesForUpdate)
{
updateEntries.Invoke(entry.DbEntry, entry.DataEntry);
}
_logger.LogInformation("Updated {TableName}", typeName);

_logger.LogDebug("Updated {TableName}", typeName);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ namespace Org.Eclipse.TractusX.PolicyHub.Service.Authentication;
public class KeycloakClaimsTransformation : IClaimsTransformation
{
private readonly JwtBearerOptions _options;
private const string ResourceAccess = "resource_access";
public const string ResourceAccess = "resource_access";

public KeycloakClaimsTransformation(IOptions<JwtBearerOptions> options)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ private static object GetRegexValue((AttributeKeyId? Key, IEnumerable<string> Va
throw new UnexpectedConditionException("There should only be one regex pattern defined");
}

if (!Regex.IsMatch(value, attributes.Values.Single()))
if (!Regex.IsMatch(value, attributes.Values.Single(), RegexOptions.Compiled, TimeSpan.FromSeconds(1)))
{
throw new ControllerArgumentException($"The provided value {value} does not match the regex pattern {attributes.Values.Single()}", nameof(value));
}
Expand Down Expand Up @@ -118,13 +118,13 @@ public async Task<PolicyResponse> GetPolicyContentAsync(PolicyContentRequest req
var multipleDefinedKey = keyCounts.Where(x => x.Value != 1);
if (multipleDefinedKey.Any())
{
throw new ControllerArgumentException($"Keys {multipleDefinedKey.Select(x => x.Key)} have been defined multiple times");
throw new ControllerArgumentException($"Keys {string.Join(",", multipleDefinedKey.Select(x => x.Key).Distinct())} have been defined multiple times");
}

var policies = await _hubRepositories.GetInstance<IPolicyRepository>().GetPolicyForOperandContent(requestData.PolicyType, requestData.Constraints.Select(x => x.Key)).ToListAsync().ConfigureAwait(false);
if (policies.Count != requestData.Constraints.Count())
{
throw new NotFoundException($"Policy for type {requestData.PolicyType} and technicalKeys {requestData.Constraints.Select(x => x.Key).Except(policies.Select(x => x.TechnicalKey))} does not exists");
throw new NotFoundException($"Policy for type {requestData.PolicyType} and technicalKeys {string.Join(",", requestData.Constraints.Select(x => x.Key).Except(policies.Select(x => x.TechnicalKey)))} does not exists");
}

var constraints = new List<Constraint>();
Expand Down Expand Up @@ -172,5 +172,5 @@ public async Task<PolicyResponse> GetPolicyContentAsync(PolicyContentRequest req
return new PolicyResponse(content, additionalAttributes);
}

private static object[] GetContext() => new object[] { "https://www.w3.org/ns/odrl.jsonld", new { cx = "https://w3id.org/catenax/v0.0.1/ns/" } };
private static IEnumerable<object> GetContext() => new object[] { "https://www.w3.org/ns/odrl.jsonld", new { cx = "https://w3id.org/catenax/v0.0.1/ns/" } };
}
67 changes: 0 additions & 67 deletions src/hub/PolicyHub.Service/Extensions/CorsExtensions.cs

This file was deleted.

81 changes: 0 additions & 81 deletions src/hub/PolicyHub.Service/HealthCheck/HealthCheckExtensions.cs

This file was deleted.

30 changes: 0 additions & 30 deletions src/hub/PolicyHub.Service/HealthCheck/HealthCheckSettings.cs

This file was deleted.

Loading

0 comments on commit d99e652

Please sign in to comment.