Adding Admin API
This commit is contained in:
@@ -0,0 +1,268 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using MicCheck.Api.ApiKeys;
|
||||
using MicCheck.Api.Data;
|
||||
using MicCheck.Api.Features;
|
||||
using MicCheck.Api.Organizations;
|
||||
using MicCheck.Api.Projects;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NUnit.Framework;
|
||||
using AppEnvironment = MicCheck.Api.Environments.Environment;
|
||||
|
||||
namespace MicCheck.Api.Tests.Unit.Admin;
|
||||
|
||||
[TestFixture]
|
||||
public class AdminApiIntegrationTests
|
||||
{
|
||||
private MicCheckWebApplicationFactory _factory = null!;
|
||||
private string _rawApiKey = null!;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_factory = new MicCheckWebApplicationFactory();
|
||||
_rawApiKey = SeedOrganizationWithApiKey();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _factory.Dispose();
|
||||
|
||||
private string SeedOrganizationWithApiKey()
|
||||
{
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
|
||||
var org = new Organization { Name = "Test Org", CreatedAt = DateTimeOffset.UtcNow };
|
||||
db.Organizations.Add(org);
|
||||
db.SaveChanges();
|
||||
|
||||
var rawKey = ApiKeyHasher.GenerateKey();
|
||||
var hashedKey = ApiKeyHasher.Hash(rawKey);
|
||||
var prefix = rawKey.Length >= 8 ? rawKey[..8] : rawKey;
|
||||
|
||||
db.ApiKeys.Add(new ApiKey
|
||||
{
|
||||
Key = hashedKey,
|
||||
Prefix = prefix,
|
||||
Name = "Test Key",
|
||||
OrganizationId = org.Id,
|
||||
IsActive = true,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
db.SaveChanges();
|
||||
|
||||
return rawKey;
|
||||
}
|
||||
|
||||
private HttpClient CreateAuthenticatedClient()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
client.DefaultRequestHeaders.Add("Authorization", $"Api-Key {_rawApiKey}");
|
||||
return client;
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAProject_ThenProjectIsReturned()
|
||||
{
|
||||
var client = CreateAuthenticatedClient();
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var org = db.Organizations.First();
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/projects", new
|
||||
{
|
||||
name = "My Project",
|
||||
organizationId = org.Id
|
||||
});
|
||||
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAFeature_ThenFeatureIsReturned()
|
||||
{
|
||||
var client = CreateAuthenticatedClient();
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var org = db.Organizations.First();
|
||||
|
||||
var project = new Project
|
||||
{
|
||||
Name = "My Project",
|
||||
OrganizationId = org.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Projects.Add(project);
|
||||
db.SaveChanges();
|
||||
|
||||
var response = await client.PostAsJsonAsync($"/api/v1/projects/{project.Id}/features", new
|
||||
{
|
||||
name = "dark_mode",
|
||||
type = "Standard",
|
||||
initialValue = (string?)null,
|
||||
description = (string?)null
|
||||
});
|
||||
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAFeature_ThenFeatureStateIsAutoCreatedForEnvironments()
|
||||
{
|
||||
var client = CreateAuthenticatedClient();
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var org = db.Organizations.First();
|
||||
|
||||
var project = new Project
|
||||
{
|
||||
Name = "My Project",
|
||||
OrganizationId = org.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Projects.Add(project);
|
||||
db.SaveChanges();
|
||||
|
||||
db.Environments.Add(new AppEnvironment
|
||||
{
|
||||
Name = "Production",
|
||||
ApiKey = "env-key-prod",
|
||||
ProjectId = project.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
db.SaveChanges();
|
||||
|
||||
await client.PostAsJsonAsync($"/api/v1/projects/{project.Id}/features", new
|
||||
{
|
||||
name = "flag_x",
|
||||
type = "Standard",
|
||||
initialValue = (string?)null,
|
||||
description = (string?)null
|
||||
});
|
||||
|
||||
using var verifyScope = _factory.Services.CreateScope();
|
||||
var verifyDb = verifyScope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var feature = verifyDb.Features.First(f => f.Name == "flag_x");
|
||||
var states = verifyDb.FeatureStates.Where(fs => fs.FeatureId == feature.Id).ToList();
|
||||
|
||||
Assert.That(states, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAnEnvironment_ThenFeatureStateIsAutoCreatedForExistingFeatures()
|
||||
{
|
||||
var client = CreateAuthenticatedClient();
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var org = db.Organizations.First();
|
||||
|
||||
var project = new Project
|
||||
{
|
||||
Name = "My Project",
|
||||
OrganizationId = org.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Projects.Add(project);
|
||||
db.Features.Add(new Feature
|
||||
{
|
||||
Name = "existing_flag",
|
||||
ProjectId = project.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
db.SaveChanges();
|
||||
|
||||
var response = await client.PostAsJsonAsync("/api/v1/environments", new
|
||||
{
|
||||
name = "Staging",
|
||||
projectId = project.Id
|
||||
});
|
||||
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created));
|
||||
|
||||
using var verifyScope = _factory.Services.CreateScope();
|
||||
var verifyDb = verifyScope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var feature = verifyDb.Features.First(f => f.Name == "existing_flag");
|
||||
var env = verifyDb.Environments.First(e => e.ProjectId == project.Id);
|
||||
var states = verifyDb.FeatureStates.Where(fs => fs.EnvironmentId == env.Id && fs.FeatureId == feature.Id).ToList();
|
||||
|
||||
Assert.That(states, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenRequestIsMissingApiKey_ThenUnauthorizedIsReturned()
|
||||
{
|
||||
var client = _factory.CreateClient();
|
||||
|
||||
var response = await client.GetAsync("/api/v1/projects?organizationId=1");
|
||||
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAFeatureWithInvalidName_ThenUnprocessableEntityIsReturned()
|
||||
{
|
||||
var client = CreateAuthenticatedClient();
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var org = db.Organizations.First();
|
||||
|
||||
var project = new Project
|
||||
{
|
||||
Name = "My Project",
|
||||
OrganizationId = org.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Projects.Add(project);
|
||||
db.SaveChanges();
|
||||
|
||||
var response = await client.PostAsJsonAsync($"/api/v1/projects/{project.Id}/features", new
|
||||
{
|
||||
name = "invalid name with spaces!",
|
||||
type = "Standard"
|
||||
});
|
||||
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.UnprocessableEntity));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingASegment_ThenSegmentIsReturned()
|
||||
{
|
||||
var client = CreateAuthenticatedClient();
|
||||
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<MicCheckDbContext>();
|
||||
var org = db.Organizations.First();
|
||||
|
||||
var project = new Project
|
||||
{
|
||||
Name = "My Project",
|
||||
OrganizationId = org.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
db.Projects.Add(project);
|
||||
db.SaveChanges();
|
||||
|
||||
var response = await client.PostAsJsonAsync($"/api/v1/projects/{project.Id}/segments", new
|
||||
{
|
||||
name = "Premium Users",
|
||||
rules = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "All",
|
||||
conditions = new[]
|
||||
{
|
||||
new { property = "plan", @operator = "Equal", value = "premium" }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Created));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
using MicCheck.Api.Audit;
|
||||
using MicCheck.Api.Data;
|
||||
using MicCheck.Api.Environments;
|
||||
using MicCheck.Api.Features;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using AppEnvironment = MicCheck.Api.Environments.Environment;
|
||||
|
||||
namespace MicCheck.Api.Tests.Unit.Environments;
|
||||
|
||||
[TestFixture]
|
||||
public class EnvironmentServiceTests
|
||||
{
|
||||
private MicCheckDbContext _db = null!;
|
||||
private EnvironmentService _service = null!;
|
||||
private const int OrganizationId = 1;
|
||||
private const int ProjectId = 1;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<MicCheckDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_db = new MicCheckDbContext(options);
|
||||
|
||||
var auditService = new Mock<AuditService>(_db, null!);
|
||||
auditService.Setup(a => a.LogAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<int>(), It.IsAny<int?>(), It.IsAny<int?>(),
|
||||
It.IsAny<string?>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_service = new EnvironmentService(_db, auditService.Object);
|
||||
|
||||
SeedBaseData();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _db.Dispose();
|
||||
|
||||
private void SeedBaseData()
|
||||
{
|
||||
_db.Organizations.Add(new MicCheck.Api.Organizations.Organization
|
||||
{
|
||||
Id = OrganizationId,
|
||||
Name = "Test Org",
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.Projects.Add(new MicCheck.Api.Projects.Project
|
||||
{
|
||||
Id = ProjectId,
|
||||
Name = "Test Project",
|
||||
OrganizationId = OrganizationId,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.SaveChanges();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAnEnvironment_ThenFeatureStateIsCreatedForEachExistingFeature()
|
||||
{
|
||||
_db.Features.Add(new Feature
|
||||
{
|
||||
Name = "feature_a",
|
||||
ProjectId = ProjectId,
|
||||
InitialValue = "hello",
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.SaveChanges();
|
||||
|
||||
var environment = await _service.CreateAsync(ProjectId, "Staging");
|
||||
|
||||
var states = await _db.FeatureStates.Where(fs => fs.EnvironmentId == environment.Id).ToListAsync();
|
||||
Assert.That(states, Has.Count.EqualTo(1));
|
||||
Assert.That(states[0].Value, Is.EqualTo("hello"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAnEnvironment_ThenAUniqueApiKeyIsGenerated()
|
||||
{
|
||||
var env1 = await _service.CreateAsync(ProjectId, "Env1");
|
||||
var env2 = await _service.CreateAsync(ProjectId, "Env2");
|
||||
|
||||
Assert.That(env1.ApiKey, Is.Not.EqualTo(env2.ApiKey));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCloningAnEnvironment_ThenEnvironmentLevelFeatureStatesAreCopied()
|
||||
{
|
||||
var source = await _service.CreateAsync(ProjectId, "Production");
|
||||
|
||||
var feature = new Feature { Name = "flag", ProjectId = ProjectId, CreatedAt = DateTimeOffset.UtcNow };
|
||||
_db.Features.Add(feature);
|
||||
_db.SaveChanges();
|
||||
|
||||
_db.FeatureStates.Add(new FeatureState
|
||||
{
|
||||
FeatureId = feature.Id,
|
||||
EnvironmentId = source.Id,
|
||||
Enabled = true,
|
||||
Value = "prod-value",
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
UpdatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.SaveChanges();
|
||||
|
||||
var cloned = await _service.CloneAsync(source.ApiKey, "Staging");
|
||||
|
||||
var clonedStates = await _db.FeatureStates
|
||||
.Where(fs => fs.EnvironmentId == cloned.Id)
|
||||
.ToListAsync();
|
||||
|
||||
Assert.That(clonedStates, Has.Count.EqualTo(1));
|
||||
Assert.That(clonedStates[0].Value, Is.EqualTo("prod-value"));
|
||||
Assert.That(clonedStates[0].Enabled, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCloningAnEnvironment_ThenIdentityOverridesAreNotCopied()
|
||||
{
|
||||
var source = await _service.CreateAsync(ProjectId, "Production");
|
||||
|
||||
var feature = new Feature { Name = "flag", ProjectId = ProjectId, CreatedAt = DateTimeOffset.UtcNow };
|
||||
_db.Features.Add(feature);
|
||||
_db.SaveChanges();
|
||||
|
||||
var identity = new MicCheck.Api.Identities.Identity
|
||||
{
|
||||
Identifier = "user-1",
|
||||
EnvironmentId = source.Id,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
};
|
||||
_db.Identities.Add(identity);
|
||||
_db.SaveChanges();
|
||||
|
||||
_db.FeatureStates.Add(new FeatureState
|
||||
{
|
||||
FeatureId = feature.Id,
|
||||
EnvironmentId = source.Id,
|
||||
IdentityId = identity.Id,
|
||||
Enabled = true,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
UpdatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.SaveChanges();
|
||||
|
||||
var cloned = await _service.CloneAsync(source.ApiKey, "Staging");
|
||||
|
||||
var clonedStates = await _db.FeatureStates
|
||||
.Where(fs => fs.EnvironmentId == cloned.Id)
|
||||
.ToListAsync();
|
||||
|
||||
Assert.That(clonedStates, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCloningAnEnvironment_ThenClonedEnvironmentHasDifferentApiKey()
|
||||
{
|
||||
var source = await _service.CreateAsync(ProjectId, "Production");
|
||||
|
||||
var cloned = await _service.CloneAsync(source.ApiKey, "Staging");
|
||||
|
||||
Assert.That(cloned.ApiKey, Is.Not.EqualTo(source.ApiKey));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
using MicCheck.Api.Audit;
|
||||
using MicCheck.Api.Data;
|
||||
using MicCheck.Api.Features;
|
||||
using MicCheck.Api.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
using AppEnvironment = MicCheck.Api.Environments.Environment;
|
||||
|
||||
namespace MicCheck.Api.Tests.Unit.Features;
|
||||
|
||||
[TestFixture]
|
||||
public class FeatureServiceTests
|
||||
{
|
||||
private MicCheckDbContext _db = null!;
|
||||
private FeatureService _service = null!;
|
||||
private const int OrganizationId = 1;
|
||||
private const int ProjectId = 1;
|
||||
private const int EnvironmentId = 1;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<MicCheckDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_db = new MicCheckDbContext(options);
|
||||
|
||||
var auditService = new Mock<AuditService>(_db, null!);
|
||||
auditService.Setup(a => a.LogAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<int>(), It.IsAny<int?>(), It.IsAny<int?>(),
|
||||
It.IsAny<string?>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_service = new FeatureService(_db, auditService.Object);
|
||||
|
||||
SeedBaseData();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _db.Dispose();
|
||||
|
||||
private void SeedBaseData()
|
||||
{
|
||||
_db.Organizations.Add(new MicCheck.Api.Organizations.Organization
|
||||
{
|
||||
Id = OrganizationId,
|
||||
Name = "Test Org",
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.Projects.Add(new MicCheck.Api.Projects.Project
|
||||
{
|
||||
Id = ProjectId,
|
||||
Name = "Test Project",
|
||||
OrganizationId = OrganizationId,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.Environments.Add(new AppEnvironment
|
||||
{
|
||||
Id = EnvironmentId,
|
||||
Name = "Production",
|
||||
ApiKey = "test-key",
|
||||
ProjectId = ProjectId,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.SaveChanges();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAFeature_ThenFeatureStateIsCreatedForEachEnvironment()
|
||||
{
|
||||
var feature = await _service.CreateAsync(ProjectId, "dark_mode", FeatureType.Standard, null, null);
|
||||
|
||||
var states = await _db.FeatureStates.Where(fs => fs.FeatureId == feature.Id).ToListAsync();
|
||||
Assert.That(states, Has.Count.EqualTo(1));
|
||||
Assert.That(states[0].EnvironmentId, Is.EqualTo(EnvironmentId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingAFeatureWithInitialValue_ThenFeatureStateHasValue()
|
||||
{
|
||||
var feature = await _service.CreateAsync(ProjectId, "flag", FeatureType.Standard, "initial-val", null);
|
||||
|
||||
var state = await _db.FeatureStates.FirstAsync(fs => fs.FeatureId == feature.Id);
|
||||
Assert.That(state.Value, Is.EqualTo("initial-val"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenProjectHas400Features_ThenCreatingAnotherThrowsDomainException()
|
||||
{
|
||||
for (var i = 0; i < 400; i++)
|
||||
{
|
||||
_db.Features.Add(new Feature
|
||||
{
|
||||
Name = $"feature_{i}",
|
||||
ProjectId = ProjectId,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
}
|
||||
_db.SaveChanges();
|
||||
|
||||
Assert.ThrowsAsync<DomainException>(() =>
|
||||
_service.CreateAsync(ProjectId, "overflow_feature", FeatureType.Standard, null, null));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenUpdatingAFeature_ThenNameAndDescriptionAreChanged()
|
||||
{
|
||||
var feature = await _service.CreateAsync(ProjectId, "old_name", FeatureType.Standard, null, "old desc");
|
||||
|
||||
var updated = await _service.UpdateAsync(feature.Id, "new_name", "new desc");
|
||||
|
||||
Assert.That(updated.Name, Is.EqualTo("new_name"));
|
||||
Assert.That(updated.Description, Is.EqualTo("new desc"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenDeletingAFeature_ThenItIsRemovedFromTheDatabase()
|
||||
{
|
||||
var feature = await _service.CreateAsync(ProjectId, "to_delete", FeatureType.Standard, null, null);
|
||||
|
||||
await _service.DeleteAsync(feature.Id);
|
||||
|
||||
var found = await _db.Features.FirstOrDefaultAsync(f => f.Id == feature.Id);
|
||||
Assert.That(found, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenListingFeatures_ThenAllProjectFeaturesAreReturned()
|
||||
{
|
||||
await _service.CreateAsync(ProjectId, "feature_a", FeatureType.Standard, null, null);
|
||||
await _service.CreateAsync(ProjectId, "feature_b", FeatureType.Standard, null, null);
|
||||
|
||||
var features = await _service.ListByProjectAsync(ProjectId);
|
||||
|
||||
Assert.That(features, Has.Count.EqualTo(2));
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,6 @@
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../src/api/MicCheck.Api/MicCheck.Api.csproj" />
|
||||
<ProjectReference Include="../../../src/infrastructure/MicCheck.Infrastructure/MicCheck.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using MicCheck.Api.Audit;
|
||||
using MicCheck.Api.Common;
|
||||
using MicCheck.Api.Data;
|
||||
using MicCheck.Api.Segments;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace MicCheck.Api.Tests.Unit.Segments;
|
||||
|
||||
[TestFixture]
|
||||
public class SegmentServiceTests
|
||||
{
|
||||
private MicCheckDbContext _db = null!;
|
||||
private SegmentService _service = null!;
|
||||
private const int OrganizationId = 1;
|
||||
private const int ProjectId = 1;
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
var options = new DbContextOptionsBuilder<MicCheckDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString())
|
||||
.Options;
|
||||
_db = new MicCheckDbContext(options);
|
||||
|
||||
var auditService = new Mock<AuditService>(_db, null!);
|
||||
auditService.Setup(a => a.LogAsync(
|
||||
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
|
||||
It.IsAny<int>(), It.IsAny<int?>(), It.IsAny<int?>(),
|
||||
It.IsAny<string?>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
_service = new SegmentService(_db, auditService.Object);
|
||||
|
||||
SeedBaseData();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _db.Dispose();
|
||||
|
||||
private void SeedBaseData()
|
||||
{
|
||||
_db.Organizations.Add(new MicCheck.Api.Organizations.Organization
|
||||
{
|
||||
Id = OrganizationId,
|
||||
Name = "Test Org",
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.Projects.Add(new MicCheck.Api.Projects.Project
|
||||
{
|
||||
Id = ProjectId,
|
||||
Name = "Test Project",
|
||||
OrganizationId = OrganizationId,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
_db.SaveChanges();
|
||||
}
|
||||
|
||||
private static SegmentRuleDefinition SingleConditionRule(
|
||||
string property = "plan",
|
||||
SegmentConditionOperator op = SegmentConditionOperator.Equal,
|
||||
string value = "premium") =>
|
||||
new(SegmentRuleType.All,
|
||||
[new SegmentConditionDefinition(property, op, value)]);
|
||||
|
||||
[Test]
|
||||
public async Task WhenCreatingASegment_ThenSegmentAndRulesArePersisted()
|
||||
{
|
||||
var rules = new[] { SingleConditionRule() };
|
||||
var segment = await _service.CreateAsync(ProjectId, "Premium Users", rules);
|
||||
|
||||
var loaded = await _db.Segments
|
||||
.Include(s => s.Rules)
|
||||
.ThenInclude(r => r.Conditions)
|
||||
.FirstAsync(s => s.Id == segment.Id);
|
||||
|
||||
Assert.That(loaded.Name, Is.EqualTo("Premium Users"));
|
||||
Assert.That(loaded.Rules, Has.Count.EqualTo(1));
|
||||
Assert.That(loaded.Rules.First().Conditions, Has.Count.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenProjectHas100Segments_ThenCreatingAnotherThrowsDomainException()
|
||||
{
|
||||
for (var i = 0; i < 100; i++)
|
||||
{
|
||||
_db.Segments.Add(new Segment
|
||||
{
|
||||
Name = $"segment_{i}",
|
||||
ProjectId = ProjectId,
|
||||
CreatedAt = DateTimeOffset.UtcNow
|
||||
});
|
||||
}
|
||||
_db.SaveChanges();
|
||||
|
||||
Assert.ThrowsAsync<DomainException>(() =>
|
||||
_service.CreateAsync(ProjectId, "overflow_segment", [SingleConditionRule()]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenSegmentHasMoreThan100Conditions_ThenCreatingThrowsDomainException()
|
||||
{
|
||||
var conditions = Enumerable.Range(0, 101)
|
||||
.Select(i => new SegmentConditionDefinition($"prop_{i}", SegmentConditionOperator.Equal, "val"))
|
||||
.ToList();
|
||||
var rules = new[] { new SegmentRuleDefinition(SegmentRuleType.All, conditions) };
|
||||
|
||||
Assert.ThrowsAsync<DomainException>(() =>
|
||||
_service.CreateAsync(ProjectId, "Too Many Conditions", rules));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenUpdatingASegment_ThenOldRulesAreReplacedWithNewRules()
|
||||
{
|
||||
var segment = await _service.CreateAsync(ProjectId, "Segment", [SingleConditionRule("plan")]);
|
||||
|
||||
var newRules = new[] { SingleConditionRule("country") };
|
||||
var updated = await _service.UpdateAsync(segment.Id, "Updated Segment", newRules);
|
||||
|
||||
var loaded = await _db.Segments
|
||||
.Include(s => s.Rules)
|
||||
.ThenInclude(r => r.Conditions)
|
||||
.FirstAsync(s => s.Id == updated.Id);
|
||||
|
||||
Assert.That(loaded.Name, Is.EqualTo("Updated Segment"));
|
||||
Assert.That(loaded.Rules, Has.Count.EqualTo(1));
|
||||
Assert.That(loaded.Rules.First().Conditions.First().Property, Is.EqualTo("country"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenDeletingASegment_ThenItIsRemovedFromTheDatabase()
|
||||
{
|
||||
var segment = await _service.CreateAsync(ProjectId, "To Delete", [SingleConditionRule()]);
|
||||
|
||||
await _service.DeleteAsync(segment.Id);
|
||||
|
||||
var found = await _db.Segments.FirstOrDefaultAsync(s => s.Id == segment.Id);
|
||||
Assert.That(found, Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task WhenListingSegments_ThenAllProjectSegmentsAreReturned()
|
||||
{
|
||||
await _service.CreateAsync(ProjectId, "Segment A", [SingleConditionRule()]);
|
||||
await _service.CreateAsync(ProjectId, "Segment B", [SingleConditionRule()]);
|
||||
|
||||
var segments = await _service.ListByProjectAsync(ProjectId);
|
||||
|
||||
Assert.That(segments, Has.Count.EqualTo(2));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user