proposal-system/api/tests/ProposalSystem.Tests/Helpers/DbContextFactory.cs
Adam Moussa ab9569d7a9 test: add ProposalNumberGenerator, LineItemService state guard, and API client interceptor tests
- ProposalNumberGenerator tests (8 tests): format validation (SHI-YYYY-NNNN),
  sequence incrementing, revision skipping, year boundary isolation, uniqueness,
  zero-padding, high sequence rollover. Uses SQLite in-memory with Postgres
  function stubs to support ExecuteSqlRawAsync.

- LineItemService state guard tests (18 tests): verifies line items cannot be
  created/bulk-updated/deleted on Approved or Sent proposals (QA-C2), confirms
  operations succeed on InReview and Revised statuses, validates
  KeyNotFoundException on missing proposals, verifies audit logging.

- API client interceptor tests (14 tests): request interceptor attaches Bearer
  token from sessionStorage (WEB-C1), handles missing/malformed token data,
  response interceptor dispatches Redux logout on 401 (WEB-M2), returns friendly
  messages for 403/404, extracts server error details, handles network errors.

- DbContextFactory updated to suppress InMemoryEventId.TransactionIgnoredWarning
  so BulkUpdateAsync tests work with in-memory provider.

- Added SqliteDbContextFactory for tests requiring relational features.

- Added Microsoft.EntityFrameworkCore.Sqlite to test project dependencies.

Total: 104 .NET tests (was 77), 26 web tests (was 12). CI already wired.
2026-05-27 18:18:44 -04:00

25 lines
905 B
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using ProposalSystem.Infrastructure.Data;
namespace ProposalSystem.Tests.Helpers;
/// <summary>
/// Creates isolated in-memory DbContext instances for unit tests.
/// Each call produces a uniquely-named database so tests don't leak state.
/// Transaction warnings are suppressed since InMemory provider does not support them.
/// </summary>
public static class DbContextFactory
{
public static ProposalDbContext Create()
{
var options = new DbContextOptionsBuilder<ProposalDbContext>()
.UseInMemoryDatabase(databaseName: $"TestDb_{Guid.NewGuid()}")
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.Options;
var context = new ProposalDbContext(options);
context.Database.EnsureCreated();
return context;
}
}