feat(arena-colosseum): lobby + constructed entry (phase 1)

Closes 5 of arena-colosseum's 16 spec shapes (1/16 → 6/16). Lobby reads
(/top, /get_fee_info, /event_info) render an empty "no event scheduled"
payload by default; /entry + /register_deck activate via admin-flipped
ColosseumSeason + ColosseumRounds config sections.

* Schema: ViewerArenaColosseumRun standalone table (unique on ViewerId)
  with jsonb run-state columns mirroring ViewerArenaTwoPickRun.
* Config sections: ColosseumSeasonConfig (event-level), ColosseumRoundsConfig
  (the 3-round bracket). Empty defaults — IsColosseumPeriod=false.
* Migration AddArenaColosseumRun (DDL only; seed rows come from the section
  ShippedDefaults via EnsureSeedDataAsync).
* DTOs: ColosseumLobbyInfo (round-level, /top + /get_fee_info), ColosseumEventInfo
  (event-level, /event_info), ColosseumOwnStatus (shared status block),
  ColosseumEntryRef, ColosseumFeeList, ColosseumUserDeck, ColosseumBattleResults,
  ColosseumRoundDetail + ColosseumGroupRow. EventInfoResponse uses explicit
  [JsonPropertyName("1"|"2"|"3")] for the string-keyed rounds shape per spec.
* Controller: ArenaColosseumController replaces the 1-action stub with
  the five lifecycle endpoints. /top emits leader_skin_id even when 0
  (project_wire_null_policy override).
* Tests: 11 controller-level tests + 6 config round-trip tests covering
  empty-season payloads, run-seeded /top round-trip, crystal/rupy entry
  debits, now_round_id mismatch rejection, deck_no_list round-trip + reject.
This commit is contained in:
gamer147
2026-06-13 12:16:22 -04:00
parent a5fe484775
commit 110867358c
30 changed files with 6474 additions and 42 deletions

View File

@@ -0,0 +1,238 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SVSim.Database;
using SVSim.Database.Enums;
using SVSim.Database.Models;
using SVSim.UnitTests.Infrastructure;
namespace SVSim.UnitTests.Controllers;
/// <summary>
/// Phase 1 entry + register-deck coverage. Activating the Colosseum season requires writing
/// a <c>ColosseumSeason</c> + <c>ColosseumRounds</c> row to <c>GameConfigs</c> — see
/// <see cref="ActivateSeasonAsync"/> for the test-only equivalent of the admin flow.
/// </summary>
public class ArenaColosseumControllerEntryTests
{
private static readonly object Envelope =
new { viewer_id = "0", steam_id = 0, steam_session_ticket = "" };
private static async Task ActivateSeasonAsync(SVSimTestFactory factory, int crystalCost = 300)
{
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
var seasonJson = JsonSerializer.Serialize(new
{
IsColosseumPeriod = true,
SeasonId = 42,
ColosseumName = "Test Cup",
DeckFormat = (int)Format.Rotation,
CrystalCost = crystalCost,
RupyCost = 3000,
TicketCost = 1,
IsAllowedFreeEntry = false,
});
await UpsertConfigAsync(db, "ColosseumSeason", seasonJson);
var roundsJson = JsonSerializer.Serialize(new
{
Rounds = new[]
{
new
{
RoundId = 1,
StartTime = DateTime.UtcNow.AddDays(-1),
EndTime = DateTime.UtcNow.AddDays(7),
Groups = new[]
{
new { Group = "", MaxBattleCount = 5, BreakthroughNumber = 4, EntryNumber = 100_000 },
},
},
},
});
await UpsertConfigAsync(db, "ColosseumRounds", roundsJson);
}
private static async Task UpsertConfigAsync(SVSimDbContext db, string section, string json)
{
var existing = await db.GameConfigs.FirstOrDefaultAsync(s => s.SectionName == section);
if (existing is null)
db.GameConfigs.Add(new GameConfigSection { SectionName = section, ValueJson = json });
else
existing.ValueJson = json;
await db.SaveChangesAsync();
}
private static async Task SetViewerCurrencyAsync(SVSimTestFactory factory, long viewerId, ulong crystals = 0, ulong rupees = 0)
{
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
var viewer = await db.Viewers.FirstAsync(v => v.Id == viewerId);
viewer.Currency.Crystals = crystals;
viewer.Currency.Rupees = rupees;
await db.SaveChangesAsync();
}
[Test]
public async Task Entry_debits_crystal_and_creates_run()
{
using var factory = new SVSimTestFactory();
await ActivateSeasonAsync(factory, crystalCost: 300);
var viewerId = await factory.SeedViewerAsync();
await SetViewerCurrencyAsync(factory, viewerId, crystals: 1000);
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/entry",
JsonContent.Create(new { consume_item_type = 1, now_round_id = 1, viewer_id = "0", steam_id = 0, steam_session_ticket = "" }));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var body = await resp.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
Assert.That(root.GetProperty("reward_list").GetArrayLength(), Is.EqualTo(1));
Assert.That(root.GetProperty("reward_list")[0].GetProperty("reward_type").GetInt32(), Is.EqualTo((int)UserGoodsType.Crystal));
Assert.That(root.GetProperty("entry_info").GetProperty("deck_format").GetInt32(), Is.EqualTo((int)Format.Rotation));
using var scope = factory.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
var run = await db.ViewerArenaColosseumRuns.FirstOrDefaultAsync(r => r.ViewerId == viewerId);
Assert.That(run, Is.Not.Null);
Assert.That(run!.SeasonId, Is.EqualTo(42));
Assert.That(run.MaxBattleCountThisRound, Is.EqualTo(5));
Assert.That(run.BreakthroughNumberThisRound, Is.EqualTo(4));
var viewerAfter = await db.Viewers.FirstAsync(v => v.Id == viewerId);
Assert.That(viewerAfter.Currency.Crystals, Is.EqualTo(700UL), "1000 - 300 cost");
}
[Test]
public async Task Entry_rejects_when_season_inactive()
{
using var factory = new SVSimTestFactory();
var viewerId = await factory.SeedViewerAsync();
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/entry",
JsonContent.Create(new { consume_item_type = 1, now_round_id = 1, viewer_id = "0", steam_id = 0, steam_session_ticket = "" }));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
var body = await resp.Content.ReadAsStringAsync();
StringAssert.Contains("colosseum_period_closed", body);
}
[Test]
public async Task Entry_rejects_when_already_in_run()
{
using var factory = new SVSimTestFactory();
await ActivateSeasonAsync(factory);
var viewerId = await factory.SeedViewerAsync();
await SetViewerCurrencyAsync(factory, viewerId, crystals: 1000);
using (var scope = factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
db.ViewerArenaColosseumRuns.Add(new ViewerArenaColosseumRun
{
ViewerId = viewerId,
EntryId = 999,
SeasonId = 42,
RoundId = 1,
DeckFormat = Format.Rotation,
});
await db.SaveChangesAsync();
}
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/entry",
JsonContent.Create(new { consume_item_type = 1, now_round_id = 1, viewer_id = "0", steam_id = 0, steam_session_ticket = "" }));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
var body = await resp.Content.ReadAsStringAsync();
StringAssert.Contains("arena_colosseum_already_in_progress", body);
}
[Test]
public async Task Entry_rejects_when_now_round_id_mismatch()
{
using var factory = new SVSimTestFactory();
await ActivateSeasonAsync(factory);
var viewerId = await factory.SeedViewerAsync();
await SetViewerCurrencyAsync(factory, viewerId, crystals: 1000);
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/entry",
JsonContent.Create(new { consume_item_type = 1, now_round_id = 7, viewer_id = "0", steam_id = 0, steam_session_ticket = "" }));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
var body = await resp.Content.ReadAsStringAsync();
StringAssert.Contains("now_round_id_mismatch", body);
}
[Test]
public async Task RegisterDeck_round_trips_deck_no_list()
{
using var factory = new SVSimTestFactory();
await ActivateSeasonAsync(factory);
var viewerId = await factory.SeedViewerAsync();
await factory.SeedDeckAsync(viewerId, Format.Rotation, number: 3, name: "Colo Deck 3");
using (var scope = factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
db.ViewerArenaColosseumRuns.Add(new ViewerArenaColosseumRun
{
ViewerId = viewerId,
EntryId = 999,
SeasonId = 42,
RoundId = 1,
DeckFormat = Format.Rotation,
});
await db.SaveChangesAsync();
}
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/register_deck",
JsonContent.Create(new { deck_no_list = "[3]", is_published = true, viewer_id = "0", steam_id = 0, steam_session_ticket = "" }));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.OK));
using var verifyScope = factory.Services.CreateScope();
var verifyDb = verifyScope.ServiceProvider.GetRequiredService<SVSimDbContext>();
var run = await verifyDb.ViewerArenaColosseumRuns.FirstAsync(r => r.ViewerId == viewerId);
Assert.That(run.RegisteredDeckNoListJson, Is.EqualTo("[3]"));
Assert.That(run.IsPublished, Is.True);
}
[Test]
public async Task RegisterDeck_rejects_when_deck_not_found()
{
using var factory = new SVSimTestFactory();
await ActivateSeasonAsync(factory);
var viewerId = await factory.SeedViewerAsync();
using (var scope = factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
db.ViewerArenaColosseumRuns.Add(new ViewerArenaColosseumRun
{
ViewerId = viewerId,
EntryId = 999,
SeasonId = 42,
RoundId = 1,
DeckFormat = Format.Rotation,
});
await db.SaveChangesAsync();
}
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/register_deck",
JsonContent.Create(new { deck_no_list = "[99]", is_published = false, viewer_id = "0", steam_id = 0, steam_session_ticket = "" }));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
var body = await resp.Content.ReadAsStringAsync();
StringAssert.Contains("deck_not_found", body);
}
}

View File

@@ -0,0 +1,138 @@
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using SVSim.Database;
using SVSim.Database.Enums;
using SVSim.Database.Models;
using SVSim.UnitTests.Infrastructure;
namespace SVSim.UnitTests.Controllers;
/// <summary>
/// Phase 1 lobby read coverage: /arena_colosseum/{top, get_fee_info, event_info}.
/// Defaults (no <c>ColosseumSeason</c> override) must render an empty "no event scheduled"
/// payload — flipping the season on is an admin operation.
/// </summary>
public class ArenaColosseumControllerTests
{
private static readonly object Envelope =
new { viewer_id = "0", steam_id = 0, steam_session_ticket = "" };
[Test]
public async Task Top_unauthenticated_returns_401()
{
using var factory = new SVSimTestFactory();
using var client = factory.CreateClient();
var resp = await client.PostAsync("/arena_colosseum/top", JsonContent.Create(Envelope));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
}
[Test]
public async Task Top_returns_no_period_when_no_season_active()
{
using var factory = new SVSimTestFactory();
var viewerId = await factory.SeedViewerAsync();
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/top", JsonContent.Create(Envelope));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var body = await resp.Content.ReadAsStringAsync();
StringAssert.Contains("\"is_colosseum_period\":false", body);
// leader_skin_id must always be emitted (even when 0) per project_wire_null_policy.
StringAssert.Contains("\"leader_skin_id\":0", body);
}
[Test]
public async Task GetFeeInfo_returns_no_period_when_no_season_active()
{
using var factory = new SVSimTestFactory();
var viewerId = await factory.SeedViewerAsync();
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/get_fee_info", JsonContent.Create(Envelope));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var body = await resp.Content.ReadAsStringAsync();
StringAssert.Contains("\"is_colosseum_period\":false", body);
// fee_list, is_unfinished_entry_exists, deck_format must be ABSENT when no event.
StringAssert.DoesNotContain("\"fee_list\"", body);
StringAssert.DoesNotContain("\"is_unfinished_entry_exists\"", body);
}
[Test]
public async Task EventInfo_returns_empty_rounds_when_default_config()
{
using var factory = new SVSimTestFactory();
var viewerId = await factory.SeedViewerAsync();
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/event_info", JsonContent.Create(Envelope));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var body = await resp.Content.ReadAsStringAsync();
// The rounds object MUST be string-keyed "1"/"2"/"3" — locking the wire shape per
// event_info.md. Custom STJ converter avoided; explicit [JsonPropertyName("1"|"2"|"3")]
// produces the same on-the-wire bytes.
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
Assert.That(root.TryGetProperty("1", out var r1), Is.True, "round '1' must be present");
Assert.That(root.TryGetProperty("2", out var r2), Is.True, "round '2' must be present");
Assert.That(root.TryGetProperty("3", out var r3), Is.True, "round '3' must be present");
// Default config → no schedule → is_now_round false on all three.
Assert.That(r1.GetProperty("is_now_round").GetBoolean(), Is.False);
Assert.That(r2.GetProperty("is_now_round").GetBoolean(), Is.False);
Assert.That(r3.GetProperty("is_now_round").GetBoolean(), Is.False);
Assert.That(r1.GetProperty("round_detail").GetArrayLength(), Is.EqualTo(0));
}
[Test]
public async Task Top_round_trips_after_entry_seeded()
{
using var factory = new SVSimTestFactory();
var viewerId = await factory.SeedViewerAsync();
// Seed an active run directly — Task 3's /entry endpoint will own creation, but
// /top must reflect the row's identity when one exists.
const long entryId = 12_345L;
using (var scope = factory.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<SVSimDbContext>();
db.ViewerArenaColosseumRuns.Add(new ViewerArenaColosseumRun
{
ViewerId = viewerId,
EntryId = entryId,
SeasonId = 1,
RoundId = 1,
DeckFormat = Format.Rotation,
LeaderSkinId = 0,
ConsumeItemType = 2,
MaxBattleCountThisRound = 5,
BreakthroughNumberThisRound = 4,
RestEntryNum = 0,
WinCount = 1,
LossCount = 0,
ResultListJson = "[1]",
});
await db.SaveChangesAsync();
}
using var client = factory.CreateAuthenticatedClient(viewerId);
var resp = await client.PostAsync("/arena_colosseum/top", JsonContent.Create(Envelope));
Assert.That(resp.StatusCode, Is.EqualTo(HttpStatusCode.OK));
var body = await resp.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(body);
var root = doc.RootElement;
Assert.That(root.GetProperty("entry_info").GetProperty("id").GetInt64(), Is.EqualTo(entryId));
Assert.That(root.GetProperty("now_round_id").GetInt32(), Is.EqualTo(1));
Assert.That(root.GetProperty("max_battle_count").GetInt32(), Is.EqualTo(5));
Assert.That(root.GetProperty("battle_results").GetProperty("win_count").GetInt32(), Is.EqualTo(1));
Assert.That(root.GetProperty("battle_results").GetProperty("result_list").GetArrayLength(), Is.EqualTo(1));
}
}