Changed the way the test-data is generated

This commit is contained in:
Jonathan Bourdon
2024-07-18 13:19:40 -04:00
parent a8b7860fd8
commit ed8f41cf96
5 changed files with 203 additions and 125 deletions

View File

@@ -1,9 +1,4 @@
using System; using Hutopy.Domain.Constants;
using System.Linq;
using System.Threading.Tasks;
using Hutopy.Domain.Constants;
using Hutopy.Infrastructure.Identity;
using Hutopy.Infrastructure.Identity.OwnedEntities;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -29,7 +24,6 @@ public static class InitializerExtensions
public class ApplicationDbContextInitializer( public class ApplicationDbContextInitializer(
ILogger<ApplicationDbContextInitializer> logger, ILogger<ApplicationDbContextInitializer> logger,
ApplicationDbContext context, ApplicationDbContext context,
ApplicationUserManager userManager,
RoleManager<IdentityRole> roleManager) RoleManager<IdentityRole> roleManager)
{ {
public async Task InitialiseAsync() public async Task InitialiseAsync()
@@ -60,7 +54,6 @@ public class ApplicationDbContextInitializer(
private async Task TrySeedAsync() private async Task TrySeedAsync()
{ {
// Default roles
var administratorRole = new IdentityRole(Roles.Administrator); var administratorRole = new IdentityRole(Roles.Administrator);
if (roleManager.Roles.All(r => r.Name != administratorRole.Name)) if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
{ {
@@ -72,47 +65,5 @@ public class ApplicationDbContextInitializer(
{ {
await roleManager.CreateAsync(roleCreator); await roleManager.CreateAsync(roleCreator);
} }
// Default users
var administrator =
new ApplicationUser { UserName = "administrator@localhost", Email = "administrator@localhost" };
if (userManager.Users.All(u => u.UserName != administrator.UserName))
{
await userManager.CreateAsync(administrator, "Administrator1!");
await userManager.AddToRolesAsync(administrator, new[] { Roles.Administrator });
}
// ADD CREATORS
await AddDefaultCreator(new ApplicationUser
{
UserName = "hutopy@localhost",
Email = "hutopy@localhost",
CreatorAlias = "hutopy",
About = "Page officielle",
Description = "Site officiel pour Hutopy. Venez-nous-y retrouver avec tous vos fans!",
EmailConfirmed = true,
ProfileColors = new ProfileColors { BannerTop = "A30E79", BannerBottom = "6B0065", Accent = "23393B", Menu = "53B93B", },
SocialNetworks =
new SocialNetworks
{
XUrl = "https://twitter.com/Hutopyinc",
FacebookUrl = "https://www.facebook.com/Hutopy",
InstagramUrl = "https://www.instagram.com/hutopy.inc/"
},
StoredDataUrls = new StoredDataUrls
{
BannerPictureUrl = "/images/usersmedia/HutopyProfile/banners/banner01.png",
ProfilePictureUrl = "/images/usersmedia/HutopyProfile/profilepictures/profileHutopyProfile01.png"
}
});
}
private async Task AddDefaultCreator(ApplicationUser hutopy)
{
if (userManager.Users.All(u => u.UserName != hutopy.UserName))
{
await userManager.CreateAsync(hutopy, "Test123!");
await userManager.AddToRolesAsync(hutopy, new[] { Roles.Creator });
}
} }
} }

View File

@@ -1,71 +0,0 @@
using Hutopy.Infrastructure.Identity;
using Hutopy.Web.Common;
using Microsoft.EntityFrameworkCore;
namespace Hutopy.Web.Contents.Data;
public static class InitializerExtensions
{
public static async Task InitialiseContentDatabaseAsync(this WebApplication app, CancellationToken ct = default)
{
using var scope = app.Services.CreateScope();
var initializer = scope.ServiceProvider.GetRequiredService<ContentDbContextInitializer>();
await initializer.InitialiseAsync(ct);
await initializer.SeedAsync(ct);
}
}
internal class ContentDbContextInitializer(
ILogger<ContentDbContextInitializer> logger,
ApplicationUserManager userManager,
ContentDbContext context)
{
public async Task InitialiseAsync(CancellationToken ct = default)
{
try
{
await context.Database.MigrateAsync(ct);
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while initialising the database.");
throw;
}
}
public async Task SeedAsync(CancellationToken ct = default)
{
try
{
var administratorUser = await userManager.FindByNameAsync("administrator@localhost");
var administratorId= Guid.Parse(administratorUser!.Id);
await TrySeedAsync(administratorId, 100, ct);
await context.SaveChangesAsync(ct);
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while seeding the database.");
throw;
}
}
private async Task TrySeedAsync(Guid creatorId, int contentCount, CancellationToken ct = default)
{
for (var c = 0; c < contentCount; c++)
{
await context.Contents.AddAsync(
new Content
{
Id = GuidHelper.GenerateUuidV7(),
CreatedBy = creatorId,
Title = $"Title {c}",
Description = $"Description {c}"
},
ct);
}
}
}

View File

@@ -11,8 +11,6 @@ public static class DependencyInjection
{ {
services.AddDbContext<ContentDbContext>(configureAction); services.AddDbContext<ContentDbContext>(configureAction);
services.AddScoped<ContentDbContextInitializer>();
return services; return services;
} }
} }

View File

@@ -6,7 +6,6 @@ using Hutopy.Infrastructure.Data;
using Hutopy.Infrastructure.Identity; using Hutopy.Infrastructure.Identity;
using Hutopy.Web; using Hutopy.Web;
using Hutopy.Web.Contents; using Hutopy.Web.Contents;
using Hutopy.Web.Contents.Data;
using Hutopy.Web.Messages; using Hutopy.Web.Messages;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -103,7 +102,7 @@ app.UseAuthorization();
// Initialize and seed the db. // Initialize and seed the db.
await app.InitialiseApplicationDatabaseAsync(); await app.InitialiseApplicationDatabaseAsync();
await app.InitialiseContentDatabaseAsync(); await app.SeedDatabaseWithTestDataOnlyIfNoDataIsPresentAsync();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())

201
src/Web/TestDataSeeder.cs Normal file
View File

@@ -0,0 +1,201 @@
using Hutopy.Domain.Constants;
using Hutopy.Infrastructure.Identity;
using Hutopy.Infrastructure.Identity.OwnedEntities;
using Hutopy.Web.Common;
using Hutopy.Web.Contents.Data;
using Hutopy.Web.Messages.Data;
namespace Hutopy.Web;
public static class WebApplicationExtensions
{
public static async Task SeedDatabaseWithTestDataOnlyIfNoDataIsPresentAsync(
this WebApplication app,
CancellationToken ct = default)
{
using var scope = app.Services.CreateScope();
var seeder = new TestDataSeeder(
scope.ServiceProvider.GetRequiredService<ApplicationUserManager>(),
scope.ServiceProvider.GetRequiredService<ContentDbContext>(),
scope.ServiceProvider.GetRequiredService<MessagingDbContext>());
await seeder.SeedAsync();
}
}
internal class TestDataSeeder(
ApplicationUserManager userManager,
ContentDbContext contentContext,
MessagingDbContext messagingContext)
{
private const string DefaultPassword = "Test123#";
public async Task SeedAsync()
{
if (contentContext.Contents.Any()) return;
_ = await CreateAdministratorAsync("admin");
_ = await CreateUserAsync("userA");
_ = await CreateUserAsync("userB");
foreach (var creator in _creators)
{
_ = await CreateCreatorAsync(creator);
var contents = GenerateContent(creator, 100);
foreach (var content in contents)
{
var messages = GenerateMessages(content, 100);
var parentMessages = messages.Where((_, index) => index % 2 == 0).ToList();
foreach (var parentMessage in parentMessages)
{
_ = GenerateReplies(content, parentMessage, 10);
}
await messagingContext.SaveChangesAsync();
}
}
}
private List<Content> GenerateContent(ApplicationUser user, int contentCount)
{
var contents = new List<Content>();
for (var c = 0; c < contentCount; c++)
{
var content = new Content
{
Id = GuidHelper.GenerateUuidV7(),
CreatedBy = Guid.Parse(user.Id),
Title = $"Title {user.UserName}-{c}",
Description = $"Description {user.UserName}-{c}"
};
contentContext.Contents.Add(content);
contents.Add(content);
}
contentContext.SaveChanges();
return contents;
}
private List<Message> GenerateMessages(Content content, int messageCount)
{
var messages = new List<Message>();
for (var m = 0; m < messageCount; m++)
{
var author = Random.Shared.GetItems(_creators, 1)[0];
var message = new Message
{
Id = GuidHelper.GenerateUuidV7(),
SubjectId = content.Id,
CreatedBy = Guid.Parse(author.Id),
Value = $"Message #{m} from {author.UserName} on {content.Title}"
};
messagingContext.Messages.Add(message);
messages.Add(message);
}
return messages;
}
private List<Message> GenerateReplies(Content content, Message parent, int replyCount)
{
var replies = new List<Message>();
for (var r = 0; r < replyCount; r++)
{
var author = Random.Shared.GetItems(_creators, 1)[0];
var message = new Message
{
Id = GuidHelper.GenerateUuidV7(),
SubjectId = content.Id,
ParentId = parent.Id,
CreatedBy = Guid.Parse(author.Id),
Value = $"Reply {r} to {parent.Value}"
};
messagingContext.Messages.Add(message);
replies.Add(message);
}
return replies;
}
private async Task<ApplicationUser> CreateAdministratorAsync(string name)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
var administrator = new ApplicationUser { UserName = $"{name}@test", Email = $"{name}@test" };
await userManager.CreateAsync(administrator, DefaultPassword);
await userManager.AddToRolesAsync(administrator, new[] { Roles.Administrator });
return administrator;
}
private async Task<ApplicationUser> CreateUserAsync(string name)
{
var user = new ApplicationUser
{
UserName = $"{name}@test",
Email = $"{name}@test",
EmailConfirmed = true,
FirstName = $"FirstName of {name}",
LastName = $"LastName of {name}"
};
await userManager.CreateAsync(user, DefaultPassword);
return user;
}
private async Task<ApplicationUser> CreateCreatorAsync(ApplicationUser creator)
{
await userManager.CreateAsync(creator, DefaultPassword);
await userManager.AddToRolesAsync(creator, new[] { Roles.Creator });
return creator;
}
private readonly static ApplicationUser Hutopy = new()
{
UserName = "hutopy@test",
Email = "hutopy@test",
EmailConfirmed = true,
CreatorAlias = "hutopy",
About = "Page officielle",
Description = "Site officiel pour Hutopy. Venez-nous-y retrouver avec tous vos fans!",
ProfileColors = new ProfileColors
{
BannerTop = "A30E79", BannerBottom = "6B0065", Accent = "23393B", Menu = "53B93B",
},
SocialNetworks =
new SocialNetworks
{
XUrl = "https://twitter.com/Hutopyinc",
FacebookUrl = "https://www.facebook.com/Hutopy",
InstagramUrl = "https://www.instagram.com/hutopy.inc/"
},
StoredDataUrls = new StoredDataUrls
{
BannerPictureUrl = "/images/usersmedia/HutopyProfile/banners/banner01.png",
ProfilePictureUrl = "/images/usersmedia/HutopyProfile/profilepictures/profileHutopyProfile01.png"
}
};
private readonly ApplicationUser[] _creators =
[
Hutopy
];
}