feat(creator): overhaul Creator flow, editor duplication, and staging setup (#83)
This pull request completely overhauls the Creator editor flow, resolves the editor duplication race condition, aligns layout/styling themes in light and dark mode, and adds Docker staging setups. ### Key Changes 1. **Creator Flow Polish**: Redesigned the editor canvas to prevent double scrolling by delegating overflow to the editor canvas layer, updated styles to a premium aesthetic. 2. **Race Condition Prevention**: Resolved Crepe editor duplication when loading or switching chapters by tracking state via shared window maps (`window.editorCache`, `window.editorStates`) and checking `_lastInitializedEditorId` synchronously in Blazor. 3. **Theme Synchronization**: Integrated explicit theme initialization (`ThemeService.InitializeAsync()`) and anchored CSS isolation selectors to correctly sync with Light (Soft Sepia) and Deep Dark theme preferences. 4. **Staging Automation**: Created staging docker configurations with `--nexus-only` flag to allow iterative development without resetting PG/Neo4j database containers. --------- Co-authored-by: Marek Jasiński <jasins.marek@gmail.com> Reviewed-on: #83 Co-authored-by: Antigravity <antigravity@google.com> Co-committed-by: Antigravity <antigravity@google.com>
This commit was merged in pull request #83.
This commit is contained in:
@@ -0,0 +1,173 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using NexusReader.Application.Features.Books.Commands;
|
||||
using NexusReader.Data.Persistence;
|
||||
using NexusReader.Domain.Entities;
|
||||
using Xunit;
|
||||
|
||||
namespace NexusReader.Application.Tests.Commands;
|
||||
|
||||
public class CreateBookTests : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly DbContextOptions<AppDbContext> _contextOptions;
|
||||
private readonly Mock<IDbContextFactory<AppDbContext>> _dbContextFactoryMock;
|
||||
|
||||
public CreateBookTests()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
_connection.Open();
|
||||
|
||||
_contextOptions = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseSqlite(_connection)
|
||||
.Options;
|
||||
|
||||
// Seed initial database schema
|
||||
using var context = new AppDbContext(_contextOptions);
|
||||
context.Database.EnsureCreated();
|
||||
|
||||
_dbContextFactoryMock = new Mock<IDbContextFactory<AppDbContext>>();
|
||||
_dbContextFactoryMock.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(() => new AppDbContext(_contextOptions));
|
||||
}
|
||||
|
||||
private NexusUser SeedUser(string userId, string tenantId)
|
||||
{
|
||||
var user = new NexusUser
|
||||
{
|
||||
Id = userId,
|
||||
UserName = $"user_{userId}",
|
||||
Email = $"{userId}@example.com",
|
||||
TenantId = tenantId,
|
||||
SubscriptionPlanId = 1
|
||||
};
|
||||
|
||||
using var context = new AppDbContext(_contextOptions);
|
||||
context.Users.Add(user);
|
||||
context.SaveChanges();
|
||||
return user;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithValidCommand_SuccessfullyCreatesBookRevisionAndIntroductionChapter()
|
||||
{
|
||||
// Arrange
|
||||
var userId = "creator-123";
|
||||
var tenantId = "tenant-abc";
|
||||
SeedUser(userId, tenantId);
|
||||
|
||||
var command = new CreateBookCommand(
|
||||
Title: "The Art of Agentic Systems",
|
||||
Description: "A masterclass on building self-healing AI agents.",
|
||||
UserId: userId,
|
||||
TenantId: tenantId
|
||||
);
|
||||
|
||||
var handler = new CreateBookCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeTrue();
|
||||
result.Value.Should().NotBeEmpty();
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
var book = await context.Books
|
||||
.Include(b => b.CurrentDraftRevision)
|
||||
.ThenInclude(r => r!.Chapters)
|
||||
.FirstOrDefaultAsync(b => b.Id == result.Value);
|
||||
|
||||
book.Should().NotBeNull();
|
||||
book!.Title.Should().Be("The Art of Agentic Systems");
|
||||
book.UserId.Should().Be(userId);
|
||||
book.TenantId.Should().Be(tenantId);
|
||||
book.CurrentDraftRevisionId.Should().NotBeNull();
|
||||
|
||||
var revision = book.CurrentDraftRevision;
|
||||
revision.Should().NotBeNull();
|
||||
revision!.VersionString.Should().Be("Working Draft");
|
||||
revision.IsPublished.Should().BeFalse();
|
||||
revision.BookId.Should().Be(book.Id);
|
||||
|
||||
revision.Chapters.Should().HaveCount(1);
|
||||
var chapter = revision.Chapters.First();
|
||||
chapter.Title.Should().Be("Introduction");
|
||||
chapter.MarkdownContent.Should().Be("# Introduction\nStart writing here...");
|
||||
chapter.SortOrder.Should().Be(1);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithEmptyTitle_ReturnsFailureResult()
|
||||
{
|
||||
// Arrange
|
||||
var command = new CreateBookCommand(
|
||||
Title: "",
|
||||
Description: "No title",
|
||||
UserId: "user-1",
|
||||
TenantId: "tenant-1"
|
||||
);
|
||||
|
||||
var handler = new CreateBookCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeFalse();
|
||||
result.Errors.Should().NotBeEmpty();
|
||||
result.Errors.First().Message.Should().Contain("title is required");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_OnDatabaseViolation_RollsBackTransaction()
|
||||
{
|
||||
// Arrange
|
||||
// We trigger a database violation by not seeding the user 'missing-user'
|
||||
// and letting the foreign key constraint fail (if SQLite enforces it).
|
||||
// If foreign keys aren't strictly enforced on SQLite by default without PRAGMA,
|
||||
// we can check if it rolls back upon other violations, or manually verify error handling.
|
||||
var command = new CreateBookCommand(
|
||||
Title: "Violating Book",
|
||||
Description: "Triggering constraint failure",
|
||||
UserId: "non-existent-user-id-constraint",
|
||||
TenantId: "tenant-1"
|
||||
);
|
||||
|
||||
// Let's force foreign key constraints on SQLite to verify rollback
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Database.ExecuteSqlRaw("PRAGMA foreign_keys = ON;");
|
||||
}
|
||||
|
||||
var handler = new CreateBookCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeFalse();
|
||||
result.Errors.Should().NotBeEmpty();
|
||||
|
||||
// Ensure nothing was committed to the DB
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
var books = await context.Books.ToListAsync();
|
||||
books.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
_connection.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using NexusReader.Application.Features.Books.Commands;
|
||||
using NexusReader.Data.Persistence;
|
||||
using NexusReader.Domain.Entities;
|
||||
using NexusReader.Domain.Exceptions;
|
||||
using Xunit;
|
||||
|
||||
namespace NexusReader.Application.Tests.Commands;
|
||||
|
||||
public class PublishBookVersionTests : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly DbContextOptions<AppDbContext> _contextOptions;
|
||||
private readonly Mock<IDbContextFactory<AppDbContext>> _dbContextFactoryMock;
|
||||
|
||||
public PublishBookVersionTests()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
_connection.Open();
|
||||
|
||||
_contextOptions = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseSqlite(_connection)
|
||||
.Options;
|
||||
|
||||
// Seed initial database schema
|
||||
using var context = new AppDbContext(_contextOptions);
|
||||
context.Database.EnsureCreated();
|
||||
|
||||
_dbContextFactoryMock = new Mock<IDbContextFactory<AppDbContext>>();
|
||||
_dbContextFactoryMock.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(() => new AppDbContext(_contextOptions));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithValidBookAndChapters_CorrectlyPublishesAndClonesChaptersWithNewGuids()
|
||||
{
|
||||
// Arrange
|
||||
var bookId = Guid.NewGuid();
|
||||
var userId = "test-user-123";
|
||||
var tenantId = "test-tenant-456";
|
||||
|
||||
var user = new NexusUser
|
||||
{
|
||||
Id = userId,
|
||||
UserName = "testuser",
|
||||
Email = "test@example.com",
|
||||
TenantId = tenantId,
|
||||
SubscriptionPlanId = 1
|
||||
};
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "My Epic Book",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
var originalDraftRevision = new BookRevision
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookId,
|
||||
VersionString = "Working Draft",
|
||||
IsPublished = false,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
var oldChapterId1 = Guid.NewGuid();
|
||||
var oldChapterId2 = Guid.NewGuid();
|
||||
|
||||
var chapter1 = new Chapter
|
||||
{
|
||||
Id = oldChapterId1,
|
||||
BookRevisionId = originalDraftRevision.Id,
|
||||
Title = "Chapter 1: The Beginning",
|
||||
MarkdownContent = "Once upon a time...",
|
||||
SortOrder = 1
|
||||
};
|
||||
|
||||
var chapter2 = new Chapter
|
||||
{
|
||||
Id = oldChapterId2,
|
||||
BookRevisionId = originalDraftRevision.Id,
|
||||
Title = "Chapter 2: The Middle",
|
||||
MarkdownContent = "Interesting things happened.",
|
||||
SortOrder = 2
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
context.BookRevisions.Add(originalDraftRevision);
|
||||
context.Chapters.Add(chapter1);
|
||||
context.Chapters.Add(chapter2);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Link the book's draft revision
|
||||
var dbBook = await context.Books.FindAsync(bookId);
|
||||
dbBook!.CurrentDraftRevisionId = originalDraftRevision.Id;
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var command = new PublishBookVersionCommand(
|
||||
BookId: bookId,
|
||||
CustomVersionString: "v1.0.0",
|
||||
UserId: userId,
|
||||
TenantId: tenantId
|
||||
);
|
||||
|
||||
var handler = new PublishBookVersionCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeTrue();
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
var updatedBook = await context.Books
|
||||
.Include(b => b.Revisions)
|
||||
.ThenInclude(r => r.Chapters)
|
||||
.FirstOrDefaultAsync(b => b.Id == bookId);
|
||||
|
||||
updatedBook.Should().NotBeNull();
|
||||
updatedBook!.LivePublishedRevisionId.Should().Be(originalDraftRevision.Id);
|
||||
updatedBook.CurrentDraftRevisionId.Should().NotBeNull();
|
||||
updatedBook.CurrentDraftRevisionId.Should().NotBe(originalDraftRevision.Id);
|
||||
|
||||
// Fetch the old draft revision (now frozen / published)
|
||||
var oldDraft = updatedBook.Revisions.FirstOrDefault(r => r.Id == originalDraftRevision.Id);
|
||||
oldDraft.Should().NotBeNull();
|
||||
oldDraft!.IsPublished.Should().BeTrue();
|
||||
oldDraft.VersionString.Should().Be("v1.0.0");
|
||||
oldDraft.PublishedAt.Should().NotBeNull();
|
||||
|
||||
// Fetch the new working draft revision
|
||||
var newDraft = updatedBook.Revisions.FirstOrDefault(r => r.Id == updatedBook.CurrentDraftRevisionId);
|
||||
newDraft.Should().NotBeNull();
|
||||
newDraft!.IsPublished.Should().BeFalse();
|
||||
newDraft.VersionString.Should().Be("Working Draft");
|
||||
|
||||
// Verify chapters were deep copied and received brand new GUIDs (Identity Reset)
|
||||
newDraft.Chapters.Should().HaveCount(2);
|
||||
|
||||
var clonedChapter1 = newDraft.Chapters.FirstOrDefault(c => c.SortOrder == 1);
|
||||
clonedChapter1.Should().NotBeNull();
|
||||
clonedChapter1!.Title.Should().Be("Chapter 1: The Beginning");
|
||||
clonedChapter1.MarkdownContent.Should().Be("Once upon a time...");
|
||||
clonedChapter1.Id.Should().NotBe(oldChapterId1); // GUID must be regenerated
|
||||
clonedChapter1.BookRevisionId.Should().Be(newDraft.Id);
|
||||
|
||||
var clonedChapter2 = newDraft.Chapters.FirstOrDefault(c => c.SortOrder == 2);
|
||||
clonedChapter2.Should().NotBeNull();
|
||||
clonedChapter2!.Title.Should().Be("Chapter 2: The Middle");
|
||||
clonedChapter2.MarkdownContent.Should().Be("Interesting things happened.");
|
||||
clonedChapter2.Id.Should().NotBe(oldChapterId2); // GUID must be regenerated
|
||||
clonedChapter2.BookRevisionId.Should().Be(newDraft.Id);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithMismatchedTenantId_ReturnsFailure()
|
||||
{
|
||||
// Arrange
|
||||
var bookId = Guid.NewGuid();
|
||||
var userId = "test-user-123";
|
||||
var tenantId = "test-tenant-456";
|
||||
|
||||
var user = new NexusUser
|
||||
{
|
||||
Id = userId,
|
||||
UserName = "testuser",
|
||||
Email = "test@example.com",
|
||||
TenantId = tenantId,
|
||||
SubscriptionPlanId = 1
|
||||
};
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "My Epic Book",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Send command with a different TenantId to check multi-tenancy isolation
|
||||
var command = new PublishBookVersionCommand(
|
||||
BookId: bookId,
|
||||
CustomVersionString: "v1.0.0",
|
||||
UserId: userId,
|
||||
TenantId: "different-tenant-789"
|
||||
);
|
||||
|
||||
var handler = new PublishBookVersionCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeFalse();
|
||||
result.Errors.Should().Contain(e => e.Message.Contains("was not found"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithMismatchedUserId_ReturnsFailure()
|
||||
{
|
||||
// Arrange
|
||||
var bookId = Guid.NewGuid();
|
||||
var userId = "test-user-123";
|
||||
var tenantId = "test-tenant-456";
|
||||
|
||||
var user = new NexusUser
|
||||
{
|
||||
Id = userId,
|
||||
UserName = "testuser",
|
||||
Email = "test@example.com",
|
||||
TenantId = tenantId,
|
||||
SubscriptionPlanId = 1
|
||||
};
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "My Epic Book",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Send command with a different UserId to check multi-tenancy isolation
|
||||
var command = new PublishBookVersionCommand(
|
||||
BookId: bookId,
|
||||
CustomVersionString: "v1.0.0",
|
||||
UserId: "different-user-789",
|
||||
TenantId: tenantId
|
||||
);
|
||||
|
||||
var handler = new PublishBookVersionCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeFalse();
|
||||
result.Errors.Should().Contain(e => e.Message.Contains("was not found"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_WithNonExistentBook_ReturnsFailure()
|
||||
{
|
||||
// Arrange
|
||||
var command = new PublishBookVersionCommand(
|
||||
BookId: Guid.NewGuid(),
|
||||
CustomVersionString: "v1.0.0",
|
||||
UserId: "user-1",
|
||||
TenantId: "tenant-1"
|
||||
);
|
||||
|
||||
var handler = new PublishBookVersionCommandHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeFalse();
|
||||
result.Errors.Should().Contain(e => e.Message.Contains("was not found"));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
_connection.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -17,5 +17,6 @@
|
||||
<ProjectReference Include="..\..\src\NexusReader.Application\NexusReader.Application.csproj" />
|
||||
<ProjectReference Include="..\..\src\NexusReader.Infrastructure\NexusReader.Infrastructure.csproj" />
|
||||
<ProjectReference Include="..\..\src\NexusReader.UI.Shared\NexusReader.UI.Shared.csproj" />
|
||||
<ProjectReference Include="..\..\src\NexusReader.Web\NexusReader.Web.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -10,7 +10,7 @@ namespace NexusReader.Application.Tests.Queries;
|
||||
|
||||
public class CheckDatabaseTest
|
||||
{
|
||||
[Fact]
|
||||
[Fact(Skip = "Requires live Postgres database in Docker")]
|
||||
public async Task PrintDatabaseStats()
|
||||
{
|
||||
var configJson = await File.ReadAllTextAsync("../../../../../src/NexusReader.Web/appsettings.json");
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
using NexusReader.Application.Queries.Creator;
|
||||
using NexusReader.Data.Persistence;
|
||||
using NexusReader.Domain.Entities;
|
||||
using NexusReader.Domain.Exceptions;
|
||||
using Xunit;
|
||||
|
||||
namespace NexusReader.Application.Tests.Queries;
|
||||
|
||||
public class CreatorDashboardTests : IDisposable
|
||||
{
|
||||
private readonly SqliteConnection _connection;
|
||||
private readonly DbContextOptions<AppDbContext> _contextOptions;
|
||||
private readonly Mock<IDbContextFactory<AppDbContext>> _dbContextFactoryMock;
|
||||
|
||||
public CreatorDashboardTests()
|
||||
{
|
||||
_connection = new SqliteConnection("DataSource=:memory:");
|
||||
_connection.Open();
|
||||
|
||||
_contextOptions = new DbContextOptionsBuilder<AppDbContext>()
|
||||
.UseSqlite(_connection)
|
||||
.Options;
|
||||
|
||||
// Seed initial database schema
|
||||
using var context = new AppDbContext(_contextOptions);
|
||||
context.Database.EnsureCreated();
|
||||
|
||||
_dbContextFactoryMock = new Mock<IDbContextFactory<AppDbContext>>();
|
||||
_dbContextFactoryMock.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(() => new AppDbContext(_contextOptions));
|
||||
}
|
||||
|
||||
private NexusUser CreateTestUser(string userId, string tenantId)
|
||||
{
|
||||
return new NexusUser
|
||||
{
|
||||
Id = userId,
|
||||
UserName = $"user_{userId}",
|
||||
Email = $"{userId}@example.com",
|
||||
TenantId = tenantId,
|
||||
SubscriptionPlanId = 1
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCreatorDashboardData_WithValidUser_ProjectsCorrectlyAndNeverLoadsMarkdownToTracker()
|
||||
{
|
||||
// Arrange
|
||||
var userId = "creator-123";
|
||||
var tenantId = "tenant-abc";
|
||||
var bookId = Guid.NewGuid();
|
||||
|
||||
var user = CreateTestUser(userId, tenantId);
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "Authored Masterpiece",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
var draft = new BookRevision
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookId,
|
||||
VersionString = "Working Draft",
|
||||
IsPublished = false,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
// Standard markdown content (length 58 characters -> estimated word count: 9 words)
|
||||
var chapter = new Chapter
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookRevisionId = draft.Id,
|
||||
Title = "Chapter One",
|
||||
MarkdownContent = "This is a content snippet that contains exactly ten words.", // 58 chars
|
||||
SortOrder = 1
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
context.BookRevisions.Add(draft);
|
||||
context.Chapters.Add(chapter);
|
||||
await context.SaveChangesAsync();
|
||||
|
||||
// Link draft revision
|
||||
var dbBook = await context.Books.FindAsync(bookId);
|
||||
dbBook!.CurrentDraftRevisionId = draft.Id;
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var query = new GetCreatorDashboardDataQuery(userId, tenantId);
|
||||
var handler = new GetCreatorDashboardDataQueryHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeTrue();
|
||||
result.Value.Should().NotBeNull();
|
||||
result.Value.Books.Should().HaveCount(1);
|
||||
|
||||
var bookDto = result.Value.Books.First();
|
||||
bookDto.Title.Should().Be("Authored Masterpiece");
|
||||
bookDto.WordCount.Should().Be(58 / 6); // projected word count calculation check
|
||||
bookDto.AggregatedReads.Should().Be(Math.Abs(bookId.GetHashCode() % 1000) + 120);
|
||||
|
||||
// Verify metrics are calculated
|
||||
result.Value.Metrics.TotalReads.Should().Be(bookDto.AggregatedReads);
|
||||
result.Value.Metrics.ActiveReaders.Should().BeGreaterThan(0);
|
||||
result.Value.Metrics.GrossRevenue.Should().Be(bookDto.AggregatedReads * 1.49m);
|
||||
result.Value.Metrics.AvgReadTimeMinutes.Should().Be(Math.Round((58 / 6) / 250.0, 1));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetCreatorDashboardData_EnforcesTenantAndUserBoundaries()
|
||||
{
|
||||
// Arrange
|
||||
var userId = "creator-123";
|
||||
var tenantId = "tenant-abc";
|
||||
var bookId = Guid.NewGuid();
|
||||
|
||||
var user = CreateTestUser(userId, tenantId);
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "Authored Masterpiece",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
// Query with mismatched tenant ID
|
||||
var queryMismatchedTenant = new GetCreatorDashboardDataQuery(userId, "different-tenant");
|
||||
var handler = new GetCreatorDashboardDataQueryHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var resultMismatchedTenant = await handler.Handle(queryMismatchedTenant, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
resultMismatchedTenant.IsSuccess.Should().BeTrue();
|
||||
resultMismatchedTenant.Value.Books.Should().BeEmpty();
|
||||
resultMismatchedTenant.Value.Metrics.TotalReads.Should().Be(0);
|
||||
|
||||
// Query with mismatched user ID
|
||||
var queryMismatchedUser = new GetCreatorDashboardDataQuery("different-user", tenantId);
|
||||
|
||||
// Act
|
||||
var resultMismatchedUser = await handler.Handle(queryMismatchedUser, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
resultMismatchedUser.IsSuccess.Should().BeTrue();
|
||||
resultMismatchedUser.Value.Books.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookRevisions_WithValidBook_ReturnsRevisionsOrderedByDate()
|
||||
{
|
||||
// Arrange
|
||||
var userId = "creator-123";
|
||||
var tenantId = "tenant-abc";
|
||||
var bookId = Guid.NewGuid();
|
||||
|
||||
var user = CreateTestUser(userId, tenantId);
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "Authored Masterpiece",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
var revision1 = new BookRevision
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookId,
|
||||
VersionString = "v1.0.0",
|
||||
IsPublished = true,
|
||||
CreatedAt = DateTime.UtcNow.AddMinutes(-5),
|
||||
PublishedAt = DateTime.UtcNow.AddMinutes(-5)
|
||||
};
|
||||
|
||||
var revision2 = new BookRevision
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
BookId = bookId,
|
||||
VersionString = "Working Draft",
|
||||
IsPublished = false,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
context.BookRevisions.Add(revision1);
|
||||
context.BookRevisions.Add(revision2);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var query = new GetBookRevisionsQuery(bookId, userId, tenantId);
|
||||
var handler = new GetBookRevisionsQueryHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act
|
||||
var result = await handler.Handle(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
result.IsSuccess.Should().BeTrue();
|
||||
result.Value.Should().HaveCount(2);
|
||||
// Ordered by CreatedAt descending
|
||||
result.Value[0].VersionString.Should().Be("Working Draft");
|
||||
result.Value[1].VersionString.Should().Be("v1.0.0");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetBookRevisions_WithMismatchedUserOrTenant_ReturnsFailure()
|
||||
{
|
||||
// Arrange
|
||||
var userId = "creator-123";
|
||||
var tenantId = "tenant-abc";
|
||||
var bookId = Guid.NewGuid();
|
||||
|
||||
var user = CreateTestUser(userId, tenantId);
|
||||
|
||||
var book = new Book
|
||||
{
|
||||
Id = bookId,
|
||||
Title = "Authored Masterpiece",
|
||||
UserId = userId,
|
||||
TenantId = tenantId
|
||||
};
|
||||
|
||||
using (var context = new AppDbContext(_contextOptions))
|
||||
{
|
||||
context.Users.Add(user);
|
||||
context.Books.Add(book);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
var handler = new GetBookRevisionsQueryHandler(_dbContextFactoryMock.Object);
|
||||
|
||||
// Act & Assert
|
||||
var queryMismatchedTenant = new GetBookRevisionsQuery(bookId, userId, "different-tenant");
|
||||
var resultTenant = await handler.Handle(queryMismatchedTenant, CancellationToken.None);
|
||||
resultTenant.IsSuccess.Should().BeFalse();
|
||||
resultTenant.Errors.Should().Contain(e => e.Message.Contains("was not found"));
|
||||
|
||||
var queryMismatchedUser = new GetBookRevisionsQuery(bookId, "different-user", tenantId);
|
||||
var resultUser = await handler.Handle(queryMismatchedUser, CancellationToken.None);
|
||||
resultUser.IsSuccess.Should().BeFalse();
|
||||
resultUser.Errors.Should().Contain(e => e.Message.Contains("was not found"));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_connection.Close();
|
||||
_connection.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
using System.Text.Json;
|
||||
using FluentAssertions;
|
||||
using NexusReader.Application.Common;
|
||||
using NexusReader.Application.DTOs.Media;
|
||||
using Xunit;
|
||||
|
||||
namespace NexusReader.Application.Tests.Services;
|
||||
|
||||
public class AutosaveEngineTests
|
||||
{
|
||||
[Fact]
|
||||
public void SerializeAndDeserialize_LocalBackupEnvelope_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
var envelope = new LocalBackupEnvelope
|
||||
{
|
||||
ChapterId = Guid.NewGuid(),
|
||||
Timestamp = DateTime.UtcNow.AddMinutes(-10),
|
||||
MarkdownContent = "# Hello Autosave"
|
||||
};
|
||||
|
||||
// Act
|
||||
var json = JsonSerializer.Serialize(envelope, AppJsonContext.Default.LocalBackupEnvelope);
|
||||
var deserialized = JsonSerializer.Deserialize(json, AppJsonContext.Default.LocalBackupEnvelope);
|
||||
|
||||
// Assert
|
||||
deserialized.Should().NotBeNull();
|
||||
deserialized!.ChapterId.Should().Be(envelope.ChapterId);
|
||||
deserialized.MarkdownContent.Should().Be(envelope.MarkdownContent);
|
||||
// Truncate milliseconds to avoid precision discrepancies in text representation
|
||||
deserialized.Timestamp.ToUniversalTime().Date.Should().Be(envelope.Timestamp.ToUniversalTime().Date);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SerializeAndDeserialize_AutosaveChapterRequest_Succeeds()
|
||||
{
|
||||
// Arrange
|
||||
var request = new AutosaveChapterRequest("# Content to Autosave");
|
||||
|
||||
// Act
|
||||
var json = JsonSerializer.Serialize(request, AppJsonContext.Default.AutosaveChapterRequest);
|
||||
var deserialized = JsonSerializer.Deserialize(json, AppJsonContext.Default.AutosaveChapterRequest);
|
||||
|
||||
// Assert
|
||||
deserialized.Should().NotBeNull();
|
||||
deserialized!.MarkdownContent.Should().Be(request.MarkdownContent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BackupEviction_CheckAgeLogic_EvictsCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
var now = DateTime.UtcNow;
|
||||
var freshTimestamp = now.AddDays(-6);
|
||||
var expiredTimestamp = now.AddDays(-8);
|
||||
|
||||
// Act & Assert
|
||||
(now - freshTimestamp).TotalDays.Should().BeLessThanOrEqualTo(7.0);
|
||||
(now - expiredTimestamp).TotalDays.Should().BeGreaterThan(7.0);
|
||||
}
|
||||
}
|
||||
@@ -51,4 +51,20 @@ public class HtmlSanitizerServiceTests
|
||||
result.Should().NotContain("alert");
|
||||
result.Should().Contain("<img src=\"x\">");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Sanitize_WithMarkdownCodeBlockContainingAngleBrackets_DoesNotStripAngleBrackets()
|
||||
{
|
||||
// Arrange
|
||||
var service = new HtmlSanitizerService();
|
||||
var input = "Here is some code:\n\n```csharp\nif (x < y && y > z) { Console.WriteLine(\"test\"); }\n```";
|
||||
|
||||
// Act
|
||||
var result = service.Sanitize(input);
|
||||
|
||||
// Assert
|
||||
result.Should().Contain("<");
|
||||
result.Should().Contain(">");
|
||||
result.Should().NotContain("<script>");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
using FluentAssertions;
|
||||
using Xunit;
|
||||
|
||||
namespace NexusReader.Application.Tests.Services;
|
||||
|
||||
public class ValidateImageSignatureTests
|
||||
{
|
||||
[Fact]
|
||||
public void Validate_PNG_WithCorrectSignature_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
byte[] pngBytes = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
string fileName = "image.png";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(pngBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeTrue();
|
||||
contentType.Should().Be("image/png");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_JPEG_WithCorrectSignature_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
byte[] jpegBytes = [0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46];
|
||||
string fileName = "photo.jpg";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(jpegBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeTrue();
|
||||
contentType.Should().Be("image/jpeg");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WEBP_WithCorrectSignature_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
byte[] webpBytes = [
|
||||
0x52, 0x49, 0x46, 0x46, // RIFF
|
||||
0x00, 0x00, 0x00, 0x00, // length
|
||||
0x57, 0x45, 0x42, 0x50 // WEBP
|
||||
];
|
||||
string fileName = "graphic.webp";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(webpBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeTrue();
|
||||
contentType.Should().Be("image/webp");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_GIF_WithCorrectSignature_ReturnsTrue()
|
||||
{
|
||||
// Arrange
|
||||
byte[] gifBytes = [
|
||||
0x47, 0x49, 0x46, 0x38, 0x39, 0x61, // GIF89a
|
||||
0x01, 0x00, 0x01, 0x00
|
||||
];
|
||||
string fileName = "animation.gif";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(gifBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeTrue();
|
||||
contentType.Should().Be("image/gif");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithMismatchingExtension_ReturnsFalse()
|
||||
{
|
||||
// Arrange: Valid PNG bytes but JPEG extension
|
||||
byte[] pngBytes = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
|
||||
string fileName = "spoofed.jpg";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(pngBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithInvalidSignature_ReturnsFalse()
|
||||
{
|
||||
// Arrange: Plain text bytes but PNG extension
|
||||
byte[] txtBytes = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77, 0x6F]; // "Hello wo"
|
||||
string fileName = "not_a_png.png";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(txtBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeFalse();
|
||||
contentType.Should().BeEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WithShortBytes_ReturnsFalse()
|
||||
{
|
||||
// Arrange
|
||||
byte[] shortBytes = [0x89, 0x50];
|
||||
string fileName = "short.png";
|
||||
|
||||
// Act
|
||||
bool isValid = ImageValidator.ValidateImageSignature(shortBytes, fileName, out string contentType);
|
||||
|
||||
// Assert
|
||||
isValid.Should().BeFalse();
|
||||
contentType.Should().BeEmpty();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user