diff options
Diffstat (limited to 'server/test')
82 files changed, 11098 insertions, 10 deletions
diff --git a/server/test/command/action_log_rollback_test.dart b/server/test/command/action_log_rollback_test.dart new file mode 100644 index 0000000..a3bf806 --- /dev/null +++ b/server/test/command/action_log_rollback_test.dart @@ -0,0 +1,52 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + GameState gs() => getIt<GameState>(); + + // The tap-to-rollback in ActionLogMenu rolls back to a chosen entry by calling + // undo (currentIndex - targetIndex) times. This verifies that semantics: the + // chosen action stays, later ones are undone, and everything stays redoable. + test('rolling back to an action undoes only the later ones (redoable)', () { + gs().clearList(); + final startMonsters = gs().currentList.whereType<Monster>().length; + + gs().action(AddMonsterCommand("Zealot", 1, false, gameState: gs())); + final afterZealotIndex = gs().commandIndex; // the entry we roll back to + gs().action( + AddMonsterCommand("Ancient Artillery (FH)", 1, false, gameState: gs()), + ); + + expect(gs().currentList.whereType<Monster>().length, startMonsters + 2); + + // Roll back to "after Zealot": undo (current - target) times. + final count = gs().commandIndex - afterZealotIndex; + expect(count, 1); + for (int k = 0; k < count; k++) { + gs().undo(); + } + + // Zealot remains; the later add is undone. + expect(gs().currentList.any((e) => e.id == "Zealot"), true); + expect( + gs().currentList.any((e) => e.id == "Ancient Artillery (FH)"), + false, + ); + + // Still redoable until a new action is taken. + for (int k = 0; k < count; k++) { + gs().redo(); + } + expect(gs().currentList.any((e) => e.id == "Ancient Artillery (FH)"), true); + }); +} diff --git a/server/test/command/activate_monster_type_command_test.dart b/server/test/command/activate_monster_type_command_test.dart new file mode 100644 index 0000000..06d82f6 --- /dev/null +++ b/server/test/command/activate_monster_type_command_test.dart @@ -0,0 +1,138 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/activate_monster_type_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() async { + await setUpGame(); + + group('ActivateMonsterTypeCommand', () { + test('should activate a monster', () { + // Arrange + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((m) => m.id == 'Zealot') + as Monster; + + expect(monster.isActive, isFalse); + + final command = ActivateMonsterTypeCommand( + 'Zealot', + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(monster.isActive, isTrue); + checkSaveState(); + }); + + test('should deactivate a monster', () { + // Arrange + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((m) => m.id == 'Zealot') + as Monster; + + final command = ActivateMonsterTypeCommand( + 'Zealot', + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(monster.isActive, isFalse); + checkSaveState(); + }); + + test('describe should return correct string for activation', () { + // Arrange + final command = ActivateMonsterTypeCommand( + 'Zealot', + true, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Activate Zealot'); + checkSaveState(); + }); + + test('describe should return correct string for deactivation', () { + // Arrange + final command = ActivateMonsterTypeCommand( + 'Zealot', + false, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Deactivate Zealot'); + checkSaveState(); + }); + + test('undo does not throw', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final gs = getIt<GameState>(); + gs.action( + ActivateMonsterTypeCommand( + 'Zealot', + true, + gameState: getIt<GameState>(), + ), + ); + expect(() => gs.undo(), returnsNormally); + }); + + test('activate in RoundState.playTurns draws ability card and sorts', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + // Enter playTurns state via DrawCommand + DrawCommand(gameState: getIt<GameState>()).execute(); + expect(getIt<GameState>().roundState, RoundState.playTurns); + // Activate should not throw even in playTurns state + expect( + () => ActivateMonsterTypeCommand( + 'Zealot', + true, + gameState: getIt<GameState>(), + ).execute(), + returnsNormally, + ); + }); + }); +} diff --git a/server/test/command/add_character_command_test.dart b/server/test/command/add_character_command_test.dart new file mode 100644 index 0000000..4fe9f1c --- /dev/null +++ b/server/test/command/add_character_command_test.dart @@ -0,0 +1,51 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import 'test_helpers.dart'; + +void _tests() { + String oldState = gameState.toString(); + AddCharacterCommand command = AddCharacterCommand( + "Hatchet", + "Jaws of the Lion", + "Arnold", + 9, + ); + command.execute(); + + test("added ok", () { + expect(gameState.currentList.first is Character, true); + expect( + (gameState.currentList.first as Character).characterState.display, + "Arnold", + ); + expect(gameState.currentList.first.id, "Hatchet"); + expect( + (gameState.currentList.first as Character).characterClass.name, + "Hatchet", + ); + expect(gameState.currentList.length, 1); + Character brute = GameMethods.getCurrentCharacters().first; + expect(brute.characterState.display, "Arnold"); + expect(brute.characterState.level, 9); + expect(gameState.unlockedClasses.first, "Hatchet"); + checkNoSideEffects(["currentList", "unlockedClasses"], oldState); + checkSaveState(); + }); + + test("description is ok", () { + expect(command.describe(), "Add Hatchet"); + //assert(_gameState.commands.last?.describe() == "Add Hatchet"); + }); + + //todo: test objective/escort/2-mini +} + +Future<void> main() async { + await setUpGame(); + _tests(); +} diff --git a/server/test/command/add_condition_command_test.dart b/server/test/command/add_condition_command_test.dart new file mode 100644 index 0000000..4e5eac2 --- /dev/null +++ b/server/test/command/add_condition_command_test.dart @@ -0,0 +1,167 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_condition_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Ancient Artillery (FH)", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + "Ancient Artillery (FH)", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + group('AddConditionCommand', () { + test('should add a condition to a character', () { + // Arrange + final command = AddConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.conditions, contains(Condition.poison)); + }); + + test('should add a condition to a monster instance', () { + // Arrange + final command = AddConditionCommand( + Condition.wound, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(monsterInstance.conditions, contains(Condition.wound)); + }); + + test('should increment chill counter when adding CHILL condition', () { + // Arrange + final command1 = AddConditionCommand( + Condition.chill, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + final command2 = AddConditionCommand( + Condition.chill, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command1.execute(); + command2.execute(); + + // Assert + expect(character.characterState.chill, 2); + // The list will contain two chill entries + expect( + character.characterState.conditions + .where((c) => c == Condition.chill) + .length, + 2, + ); + }); + + test('should not add a duplicate non-stacking condition', () { + // Arrange + final command1 = AddConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + final command2 = AddConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command1.execute(); + command2.execute(); + + // Assert + expect( + character.characterState.conditions + .where((c) => c == Condition.poison) + .length, + 1, + ); + }); + + test('describe should return correct string for character', () { + // Arrange + final command = AddConditionCommand( + Condition.muddle, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add condition: muddle'); + }); + + test('describe should return correct string for monster', () { + // Arrange + final command = AddConditionCommand( + Condition.stun, + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add condition: stun'); + }); + }); +} diff --git a/server/test/command/add_cs_party_card_command_test.dart b/server/test/command/add_cs_party_card_command_test.dart new file mode 100644 index 0000000..c954be6 --- /dev/null +++ b/server/test/command/add_cs_party_card_command_test.dart @@ -0,0 +1,80 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_cs_party_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + // Using a non-CS character is fine for testing the command's logic + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('AddCSPartyCardCommand', () { + test('should add a CS party card to a character deck', () { + // Arrange + final command = AddCSPartyCardCommand( + character.id, + 1, + gameState: getIt<GameState>(), + ); + final modifierDeck = character.characterState.modifierDeck; + final initialCardCount = modifierDeck.drawPileSize; + + // Act + command.execute(); + + // Assert + final finalCardCount = modifierDeck.drawPileSize; + expect(finalCardCount, initialCardCount + 1); + expect(modifierDeck.hasCard('party/1'), isTrue); + checkSaveState(); + }); + + test('should add a different CS party card to a character deck', () { + // Arrange + final command = AddCSPartyCardCommand( + character.id, + 2, + gameState: getIt<GameState>(), + ); + final modifierDeck = character.characterState.modifierDeck; + final initialCardCount = modifierDeck.drawPileSize; + + // Act + command.execute(); + + // Assert + final finalCardCount = modifierDeck.drawPileSize; + expect(finalCardCount, initialCardCount + 1); + expect(modifierDeck.hasCard('party/2'), isTrue); + checkSaveState(); + }); + + test('describe should return correct string', () { + // Arrange + final command = AddCSPartyCardCommand( + 'Blinkblade', + 1, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Blinkblade add party card 1'); + }); + }); +} diff --git a/server/test/command/add_faction_card_command_test.dart b/server/test/command/add_faction_card_command_test.dart new file mode 100644 index 0000000..e5fa382 --- /dev/null +++ b/server/test/command/add_faction_card_command_test.dart @@ -0,0 +1,100 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_faction_card_command.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late String factionCardId; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + // Get a valid faction card ID to use in tests + factionCardId = GameMethods.getFactionCards('Military').first.gfx; + }); + + group('AddFactionCardCommand', () { + test('should add a faction card to a character deck', () { + // Arrange + final command = AddFactionCardCommand( + character.id, + factionCardId, + true, + gameState: getIt<GameState>(), + ); + final modifierDeck = character.characterState.modifierDeck; + + // Act + command.execute(); + + // Assert + expect(modifierDeck.hasCard(factionCardId), isTrue); + }); + + test('should remove a faction card from a character deck', () { + // Arrange + final modifierDeck = character.characterState.modifierDeck; + // Add the card first + AddFactionCardCommand( + character.id, + factionCardId, + true, + gameState: getIt<GameState>(), + ).execute(); + expect(modifierDeck.hasCard(factionCardId), isTrue); + + final command = AddFactionCardCommand( + character.id, + factionCardId, + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(modifierDeck.hasCard(factionCardId), isFalse); + }); + + test('describe should return correct string for adding a card', () { + // Arrange + final command = AddFactionCardCommand( + 'Blinkblade', + factionCardId, + true, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Blinkblade add faction card'); + }); + + test('describe should return correct string for removing a card', () { + // Arrange + final command = AddFactionCardCommand( + 'Blinkblade', + factionCardId, + false, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Blinkblade remove faction card'); + }); + }); +} diff --git a/server/test/command/add_loot_card_command_test.dart b/server/test/command/add_loot_card_command_test.dart new file mode 100644 index 0000000..7ff8c0d --- /dev/null +++ b/server/test/command/add_loot_card_command_test.dart @@ -0,0 +1,55 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + // A scenario is needed to initialize the loot deck + SetCampaignCommand("Frosthaven").execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('AddLootCardCommand', () { + test('should add a specified loot card to the deck', () { + // Arrange + final command = AddLootCardCommand( + 'lumber', + gameState: getIt<GameState>(), + ); + final lootDeck = getIt<GameState>().lootDeck; + final initialCardCount = lootDeck.drawPileSize; + + // Act + command.execute(); + + // Assert + expect(lootDeck.drawPileSize, initialCardCount + 1); + checkSaveState(); + }); + + test('describe should return the correct string', () { + // Arrange + final command = AddLootCardCommand( + 'hides', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add hides Loot Card'); + }); + }); +} diff --git a/server/test/command/add_monster_command_test.dart b/server/test/command/add_monster_command_test.dart new file mode 100644 index 0000000..783346f --- /dev/null +++ b/server/test/command/add_monster_command_test.dart @@ -0,0 +1,95 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + }); + + group('AddMonsterCommand', () { + test('should add a monster to the game', () { + // Arrange + final command = AddMonsterCommand( + "Ancient Artillery (FH)", + 2, + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + expect(getIt<GameState>().currentList, contains(monster)); + expect(monster.id, "Ancient Artillery (FH)"); + expect(monster.level, 2); + expect(monster.isAlly, isFalse); + }); + + test('should add an allied monster', () { + // Arrange + final command = AddMonsterCommand( + "Ancient Artillery (FH)", + 2, + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + expect(monster.isAlly, isTrue); + }); + + test('should use game level if monster level is null', () { + // Arrange + SetLevelCommand(3, null).execute(); + final command = AddMonsterCommand( + "Ancient Artillery (FH)", + null, + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + expect(monster.level, 3); + }); + + test('describe should return correct string', () { + // Arrange + final command = AddMonsterCommand( + "Ancient Artillery (FH)", + 2, + false, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add Ancient Artillery'); + }); + }); +} diff --git a/server/test/command/add_perk_command_test.dart b/server/test/command/add_perk_command_test.dart new file mode 100644 index 0000000..3cac038 --- /dev/null +++ b/server/test/command/add_perk_command_test.dart @@ -0,0 +1,84 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_perk_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('AddPerkCommand', () { + test('should add a perk to a character', () { + // Arrange + final perkIndex = 0; + final command = AddPerkCommand(character.id, perkIndex); + final initialPerkState = character.characterState.perkList[perkIndex]; + + // Act + command.execute(); + + // Assert + final finalPerkState = character.characterState.perkList[perkIndex]; + expect(initialPerkState, isFalse); + expect(finalPerkState, isTrue); + checkSaveState(); + }); + + test('should remove an already added perk from a character', () { + // Arrange + final perkIndex = 0; + // Add the perk first + AddPerkCommand(character.id, perkIndex).execute(); + final initialPerkState = character.characterState.perkList[perkIndex]; + final command = AddPerkCommand(character.id, perkIndex); + + // Act + command.execute(); + + // Assert + final finalPerkState = character.characterState.perkList[perkIndex]; + expect(initialPerkState, isTrue); + expect(finalPerkState, isFalse); + checkSaveState(); + }); + + test('describe should return "Remove" when adding a perk (due to bug)', () { + // Arrange + // The perk is not yet added, so perkList[index] is false. + final command = AddPerkCommand(character.id, 0); + expect(character.characterState.perkList[0], isFalse); + + // Act & Assert + // The describe method has a bug: it says "Remove" when it should say "Add". + expect(command.describe(), "Remove '${character.id}' Perk 0"); + }); + + test('describe should return "Add" when removing a perk (due to bug)', () { + // Arrange + // Add the perk first so perkList[index] is true. + AddPerkCommand(character.id, 0).execute(); + expect(character.characterState.perkList[0], isTrue); + final command = AddPerkCommand(character.id, 0); + + // Act & Assert + // The describe method has a bug: it says "Add" when it should say "Remove". + expect(command.describe(), "Add '${character.id}' Perk 0"); + }); + }); +} diff --git a/server/test/command/add_special_loot_card_command_test.dart b/server/test/command/add_special_loot_card_command_test.dart new file mode 100644 index 0000000..39439b7 --- /dev/null +++ b/server/test/command/add_special_loot_card_command_test.dart @@ -0,0 +1,100 @@ +// ignore_for_file: no-magic-number + +import 'package:collection/collection.dart'; +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_special_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + //getIt<GameState>().reset(); + // A scenario is needed to initialize the loot deck + SetCampaignCommand("Frosthaven").execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('AddSpecialLootCardCommand', () { + test('should add special loot card 1418', () { + // Arrange + final command = AddSpecialLootCardCommand( + 1418, + gameState: getIt<GameState>(), + ); + final lootDeck = getIt<GameState>().lootDeck; + final initialCardCount = lootDeck.drawPileSize; + + // Act + command.execute(); + + // Assert + expect(lootDeck.drawPileSize, initialCardCount + 1); + final card = lootDeck.drawPileContents.firstWhereOrNull( + (card) => card.id == 1418, + ); + expect(card?.gfx, 'special 1418'); + checkSaveState(); + }); + + test('should add special loot card 1419', () { + // Arrange + final command = AddSpecialLootCardCommand( + 1419, + gameState: getIt<GameState>(), + ); + final lootDeck = getIt<GameState>().lootDeck; + final initialCardCount = lootDeck.drawPileSize; + + // Act + command.execute(); + + // Assert + expect(lootDeck.drawPileSize, initialCardCount + 1); + final card = lootDeck.drawPileContents.firstWhereOrNull( + (card) => card.id == 1419, + ); + expect(card?.gfx, 'special 1419'); + checkSaveState(); + }); + + test('should not add other cards', () { + // Arrange + final command = AddSpecialLootCardCommand( + 9999, + gameState: getIt<GameState>(), + ); + final lootDeck = getIt<GameState>().lootDeck; + final initialCardCount = lootDeck.drawPileSize; + + // Act + command.execute(); + + // Assert + expect(lootDeck.drawPileSize, initialCardCount); + // Since no change is expected, we don't call checkSaveState() + }); + + test('describe should return correct string', () { + // Arrange + final command = AddSpecialLootCardCommand( + 1418, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add Special loot card 1418'); + }); + }); +} diff --git a/server/test/command/add_standee_command_test.dart b/server/test/command/add_standee_command_test.dart new file mode 100644 index 0000000..63b0618 --- /dev/null +++ b/server/test/command/add_standee_command_test.dart @@ -0,0 +1,121 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late Monster monster; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Ancient Artillery (FH)", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + }); + + group('AddStandeeCommand', () { + test('should add a standee to a monster', () { + // Arrange + final command = AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final updatedMonster = + getIt<GameState>().currentList.firstWhere((m) => m.id == monster.id) + as Monster; + expect(updatedMonster.monsterInstances.length, 1); + expect(updatedMonster.monsterInstances.first.standeeNr, 1); + checkSaveState(); + }); + + test('should add a summon to a character', () { + // Arrange + final summonData = SummonData(1, 'Test Summon', 10, 2, 2, 0, 'test_gfx'); + final command = AddStandeeCommand( + 1, + summonData, + character.id, + MonsterType.summon, + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final updatedCharacter = + getIt<GameState>().currentList.firstWhere((c) => c.id == character.id) + as Character; + expect(updatedCharacter.characterState.summonList.length, 1); + expect( + updatedCharacter.characterState.summonList.first.name, + 'Test Summon', + ); + checkSaveState(); + }); + + test('describe should return correct string for a monster standee', () { + // Arrange + final command = AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add Ancient Artillery (FH) 1'); + }); + + test('describe should return correct string for a summon', () { + // Arrange + final summonData = SummonData(1, 'Test Summon', 10, 2, 2, 0, 'test_gfx'); + final command = AddStandeeCommand( + 1, + summonData, + character.id, + MonsterType.summon, + true, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add Test Summon 1'); + }); + }); +} diff --git a/server/test/command/amd_add_minus_one_command_test.dart b/server/test/command/amd_add_minus_one_command_test.dart new file mode 100644 index 0000000..4a354c8 --- /dev/null +++ b/server/test/command/amd_add_minus_one_command_test.dart @@ -0,0 +1,116 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/amd_add_minus_one_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('AmdAddMinusOneCommand', () { + test('should add a minus one card to a character deck', () { + // Arrange + final command = AmdAddMinusOneCommand( + character.id, + gameState: getIt<GameState>(), + ); + final modifierDeck = character.characterState.modifierDeck; + int initialCount = 0; + modifierDeck.drawPileContents.toList().forEach((element) { + if (element.gfx == 'minus1') { + initialCount++; + } + }); + + // Act + command.execute(); + + // Assert + int finalCount = 0; + modifierDeck.drawPileContents.toList().forEach((element) { + if (element.gfx == 'minus1') { + finalCount++; + } + }); + expect(finalCount, initialCount + 1); + }); + + test('should add a minus one card to the monster deck', () { + // Arrange + final command = AmdAddMinusOneCommand('', gameState: getIt<GameState>()); + final modifierDeck = getIt<GameState>().modifierDeck; + int initialCount = 0; + modifierDeck.drawPileContents.toList().forEach((element) { + if (element.gfx == 'minus1') { + initialCount++; + } + }); + + // Act + command.execute(); + + // Assert + int finalCount = 0; + modifierDeck.drawPileContents.toList().forEach((element) { + if (element.gfx == 'minus1') { + finalCount++; + } + }); + expect(finalCount, initialCount + 1); + }); + + test('should add a minus one card to the allies deck', () { + // Arrange + final command = AmdAddMinusOneCommand( + 'allies', + gameState: getIt<GameState>(), + ); + final modifierDeck = getIt<GameState>().modifierDeckAllies; + int initialCount = 0; + modifierDeck.drawPileContents.toList().forEach((element) { + if (element.gfx == 'minus1') { + initialCount++; + } + }); + + // Act + command.execute(); + + // Assert + int finalCount = 0; + modifierDeck.drawPileContents.toList().forEach((element) { + if (element.gfx == 'minus1') { + finalCount++; + } + }); + expect(finalCount, initialCount + 1); + }); + + test('describe should return correct string', () { + // Arrange + final command = AmdAddMinusOneCommand( + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add minus one'); + }); + }); +} diff --git a/server/test/command/amd_cassandra_special_command_test.dart b/server/test/command/amd_cassandra_special_command_test.dart new file mode 100644 index 0000000..19fde22 --- /dev/null +++ b/server/test/command/amd_cassandra_special_command_test.dart @@ -0,0 +1,63 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_cassandra_special_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('AMDCassandraSpecialCommand', () { + test('should set cassandraSpecial to true on main deck', () { + AMDCassandraSpecialCommand( + '', + true, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().modifierDeck.cassandraSpecial, isTrue); + checkSaveState(); + }); + + test('should set cassandraSpecial to false on main deck', () { + AMDCassandraSpecialCommand( + '', + true, + gameState: getIt<GameState>(), + ).execute(); + AMDCassandraSpecialCommand( + '', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().modifierDeck.cassandraSpecial, isFalse); + checkSaveState(); + }); + + test('describe when on returns leave-revealed string', () { + final command = AMDCassandraSpecialCommand( + 'Blinkblade', + true, + gameState: getIt<GameState>(), + ); + expect( + command.describe(), + 'Leave revealed cards on top of Blinkblade deck', + ); + }); + + test('describe when off returns turned-off string', () { + final command = AMDCassandraSpecialCommand( + 'Blinkblade', + false, + gameState: getIt<GameState>(), + ); + expect( + command.describe(), + 'Cassandra Special turned off for Blinkblade deck', + ); + }); + }); +} diff --git a/server/test/command/amd_imbue1_command_test.dart b/server/test/command/amd_imbue1_command_test.dart new file mode 100644 index 0000000..6d1166e --- /dev/null +++ b/server/test/command/amd_imbue1_command_test.dart @@ -0,0 +1,47 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_imbue1_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_imbue_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + AMDRemoveImbueCommand(gameState: getIt<GameState>()).execute(); + }); + + group('AMDImbue1Command', () { + test('should set imbue1 on the monster modifier deck', () { + // Arrange + final command = AMDImbue1Command(gameState: getIt<GameState>()); + final monsterDeck = getIt<GameState>().modifierDeck; + expect(monsterDeck.imbuement, 0); + + expect(monsterDeck.drawPileSize, 20); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 1); + expect(monsterDeck.drawPileSize, 22); + //todo: check the cards in the deck + checkSaveState(); + }); + + test('describe should return correct string', () { + // Arrange + final command = AMDImbue1Command(gameState: getIt<GameState>()); + + // Act & Assert + expect(command.describe(), 'Imbue Monster Deck'); + }); + }); +} diff --git a/server/test/command/amd_imbue2_command_test.dart b/server/test/command/amd_imbue2_command_test.dart new file mode 100644 index 0000000..0e96a35 --- /dev/null +++ b/server/test/command/amd_imbue2_command_test.dart @@ -0,0 +1,66 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_imbue1_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue2_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_imbue_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + AMDRemoveImbueCommand(gameState: getIt<GameState>()).execute(); + }); + + group('AMDImbue2Command', () { + test('should set imbue2 on the monster modifier deck', () { + // Arrange + final command = AMDImbue2Command(gameState: getIt<GameState>()); + final monsterDeck = getIt<GameState>().modifierDeck; + expect(monsterDeck.imbuement, 0); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 2); + expect(monsterDeck.drawPileSize, 24); + //todo: check actual cards + checkSaveState(); + }); + + test( + 'should set imbue2 on the monster modifier deck after imbue 1 set', + () { + // Arrange + AMDImbue1Command(gameState: getIt<GameState>()).execute(); + final command = AMDImbue2Command(gameState: getIt<GameState>()); + final monsterDeck = getIt<GameState>().modifierDeck; + expect(monsterDeck.imbuement, 1); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 2); + expect(monsterDeck.drawPileSize, 24); + //todo: check actual cards + checkSaveState(); + }, + ); + + test('describe should return correct string', () { + // Arrange + final command = AMDImbue2Command(gameState: getIt<GameState>()); + + // Act & Assert + expect(command.describe(), 'Advanced Imbue Monster Deck'); + }); + }); +} diff --git a/server/test/command/amd_remove_imbue_command_test.dart b/server/test/command/amd_remove_imbue_command_test.dart new file mode 100644 index 0000000..7af6095 --- /dev/null +++ b/server/test/command/amd_remove_imbue_command_test.dart @@ -0,0 +1,105 @@ +// ignore_for_file: no-magic-number, no-empty-block + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_perk_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue1_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue2_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_imbue_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() {}); + + group('AMDRemoveImbueCommand', () { + test('should remove imbuement from the monster modifier deck', () { + // Arrange + final monsterDeck = getIt<GameState>().modifierDeck; + // Add imbuement first to ensure there is something to remove. + AMDImbue1Command(gameState: getIt<GameState>()).execute(); + expect(monsterDeck.imbuement, 1); + + final command = AMDRemoveImbueCommand(gameState: getIt<GameState>()); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 0); + expect(monsterDeck.drawPileSize, 20); + checkSaveState(); + }); + + test('should remove imbuement from the monster modifier deck 2', () { + // Arrange + final monsterDeck = getIt<GameState>().modifierDeck; + // Add imbuement first to ensure there is something to remove. + AMDImbue2Command(gameState: getIt<GameState>()).execute(); + expect(monsterDeck.imbuement, 2); + + final command = AMDRemoveImbueCommand(gameState: getIt<GameState>()); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 0); + expect(monsterDeck.drawPileSize, 20); + checkSaveState(); + }); + + test('should remove imbuement from the monster modifier deck both', () { + // Arrange + final monsterDeck = getIt<GameState>().modifierDeck; + // Add imbuement first to ensure there is something to remove. + AMDImbue1Command(gameState: getIt<GameState>()).execute(); + AMDImbue2Command(gameState: getIt<GameState>()).execute(); + expect(monsterDeck.imbuement, 2); + + final command = AMDRemoveImbueCommand(gameState: getIt<GameState>()); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 0); + expect(monsterDeck.drawPileSize, 20); + checkSaveState(); + }); + + test('should not remove hail special', () { + // Arrange + final monsterDeck = getIt<GameState>().modifierDeck; + // Add imbuement first to ensure there is something to remove. + AddCharacterCommand("Hail", "Mercenary Packs", "Hail", 1).execute(); + AddPerkCommand("Hail", 17).execute(); + AMDImbue2Command(gameState: getIt<GameState>()).execute(); + expect(monsterDeck.imbuement, 2); + + final command = AMDRemoveImbueCommand(gameState: getIt<GameState>()); + + // Act + command.execute(); + + // Assert + expect(monsterDeck.imbuement, 0); + expect(monsterDeck.drawPileSize, 21); + checkSaveState(); + }); + + test('describe should return correct string', () { + // Arrange + final command = AMDRemoveImbueCommand(gameState: getIt<GameState>()); + + // Act & Assert + expect(command.describe(), 'Remove Imbuement'); + }); + }); +} diff --git a/server/test/command/amd_remove_minus_1_command_test.dart b/server/test/command/amd_remove_minus_1_command_test.dart new file mode 100644 index 0000000..715dc1d --- /dev/null +++ b/server/test/command/amd_remove_minus_1_command_test.dart @@ -0,0 +1,157 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/amd_add_minus_one_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_minus_1_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +int _getMinusOnes(ModifierDeck deck) { + int count = 0; + for (var item in deck.drawPileContents.toList()) { + if (item.gfx == "minus1") { + count++; + } + } + return count; +} + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + //getIt<GameState>().reset(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('AMDRemoveMinus1Command', () { + test('should remove a minus one card from a character deck', () { + // Arrange + final modifierDeck = character.characterState.modifierDeck; + int initialCount = _getMinusOnes(modifierDeck); + expect(initialCount, 5); + + final command = AMDRemoveMinus1Command( + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCount = _getMinusOnes(modifierDeck); + expect(finalCount, initialCount - 1); + }); + + test('should remove a minus one card from a character deck', () { + // Arrange + final modifierDeck = character.characterState.modifierDeck; + AmdAddMinusOneCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); // Add one first + int initialCount = _getMinusOnes(modifierDeck); + expect(initialCount, 6); + + final command = AMDRemoveMinus1Command( + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCount = _getMinusOnes(modifierDeck); + expect(finalCount, initialCount - 1); + }); + + test('should remove a minus one card from a character deck', () { + // Arrange + final modifierDeck = character.characterState.modifierDeck; + AmdAddMinusOneCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); // Add one first + int initialCount = _getMinusOnes(modifierDeck); + expect(initialCount, 6); + + final command = AMDRemoveMinus1Command( + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + command.execute(); + command.execute(); + command.execute(); + command.execute(); + command.execute(); + command.execute(); + command.execute(); + command.execute(); + command.execute(); + + // Assert + final finalCount = _getMinusOnes(modifierDeck); + expect(finalCount, 0); + }); + + test('should remove a minus one card from the monster deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeck; + //AmdAddMinusOneCommand('', gameState: getIt<GameState>()).execute(); // Add one first + final initialCount = _getMinusOnes(modifierDeck); + final command = AMDRemoveMinus1Command('', gameState: getIt<GameState>()); + + // Act + command.execute(); + + // Assert + final finalCount = _getMinusOnes(modifierDeck); + expect(finalCount, initialCount - 1); + }); + + test('should remove a minus one card from the allies deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeckAllies; + //AmdAddMinusOneCommand('allies', gameState: getIt<GameState>()).execute(); // Add one first + final initialCount = _getMinusOnes(modifierDeck); + final command = AMDRemoveMinus1Command( + 'allies', + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCount = _getMinusOnes(modifierDeck); + expect(finalCount, initialCount - 1); + }); + + test('describe should return correct string', () { + // Arrange + final command = AMDRemoveMinus1Command( + 'Blinkblade', + gameState: getIt<GameState>(), + ); + command.execute(); + + // Act & Assert + expect(command.describe(), 'Remove minus one'); + }); + }); +} diff --git a/server/test/command/amd_remove_minus_2_command_test.dart b/server/test/command/amd_remove_minus_2_command_test.dart new file mode 100644 index 0000000..49963e9 --- /dev/null +++ b/server/test/command/amd_remove_minus_2_command_test.dart @@ -0,0 +1,112 @@ +// ignore_for_file: avoid-non-null-assertion + +import 'package:collection/collection.dart'; +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_remove_minus_2_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + final command = SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ); //setting scenario resets the decks + // Act + command.execute(); + }); + + group('AMDRemoveMinus2Command', () { + test('should remove a minus two card from the monster deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeck; + final command = AMDRemoveMinus2Command( + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + final card = modifierDeck.drawPileContents.toList().firstWhereOrNull(( + it, + ) { + return it.gfx == 'minus2'; + }); + // Assert + expect(card, null); + }); + + test('should add back a removed minus two card from the monster deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeck; + final command = AMDRemoveMinus2Command( + false, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + final card = modifierDeck.drawPileContents.toList().firstWhereOrNull(( + it, + ) { + return it.gfx == 'minus2'; + }); + // Assert + expect(card, null); + + //add back + AMDRemoveMinus2Command(false, gameState: getIt<GameState>()).execute(); + final card2 = modifierDeck.drawPileContents.toList().firstWhereOrNull(( + it, + ) { + return it.gfx == 'minus2'; + }); + // Assert + expect(card2 == null, false); + expect(card2!.gfx, 'minus2'); + }); + + test('should remove a minus two card from the allies deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeckAllies; + final command = AMDRemoveMinus2Command( + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + final card = modifierDeck.drawPileContents.toList().firstWhereOrNull(( + it, + ) { + return it.gfx == 'minus2'; + }); + + // Assert + expect(card, null); + }); + + test('describe should return correct string', () { + // Arrange + final command = AMDRemoveMinus2Command( + false, + gameState: getIt<GameState>(), + ); + command.execute(); + + // Act & Assert + expect(command.describe(), 'Remove minus two'); + }); + }); +} diff --git a/server/test/command/amd_remove_plus_0_command_test.dart b/server/test/command/amd_remove_plus_0_command_test.dart new file mode 100644 index 0000000..3cc5360 --- /dev/null +++ b/server/test/command/amd_remove_plus_0_command_test.dart @@ -0,0 +1,119 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_remove_plus_0_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + // Setting a scenario resets the modifier decks to their default state. + final command = SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ); + command.execute(); + }); + + group('AmdRemovePlus0Command', () { + test('should remove a plus zero card from the monster deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeck; + final initialCount = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + final command = AmdRemovePlus0Command( + "", + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCount = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + expect(finalCount, initialCount - 1); + }); + + test('should add back a removed plus zero card to the monster deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeck; + final initialCount = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + final command = AmdRemovePlus0Command( + "", + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); // Remove one card + + // Assert + final countAfterRemove = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + expect(countAfterRemove, initialCount - 1); + + // Act: Add the card back + AmdRemovePlus0Command("", false, gameState: getIt<GameState>()).execute(); + + // Assert + final countAfterAdd = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + expect(countAfterAdd, initialCount); + }); + + test('should remove a plus zero card from the allies deck', () { + // Arrange + final modifierDeck = getIt<GameState>().modifierDeckAllies; + final initialCount = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + final command = AmdRemovePlus0Command( + "allies", + true, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCount = modifierDeck.drawPileContents + .toList() + .where((c) => c.gfx == 'plus0') + .length; + expect(finalCount, initialCount - 1); + }); + + test('describe should return correct string', () { + // Arrange + final command = AmdRemovePlus0Command( + "", + true, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Remove plus zero'); + }); + }); +} diff --git a/server/test/command/amd_reveal_command_test.dart b/server/test/command/amd_reveal_command_test.dart new file mode 100644 index 0000000..98fdb8d --- /dev/null +++ b/server/test/command/amd_reveal_command_test.dart @@ -0,0 +1,50 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_reveal_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('AMDRevealCommand', () { + test('should set revealedCount on the main modifier deck', () { + final command = AMDRevealCommand( + amount: 2, + name: 'Monsters', + gameState: getIt<GameState>(), + ); + command.execute(); + expect(getIt<GameState>().modifierDeck.revealedCount, 2); + checkSaveState(); + }); + + test('should set revealedCount to zero when amount is 0', () { + AMDRevealCommand( + amount: 3, + name: 'Monsters', + gameState: getIt<GameState>(), + ).execute(); + AMDRevealCommand( + amount: 0, + name: 'Monsters', + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().modifierDeck.revealedCount, 0); + }); + + test('describe should include the amount', () { + final command = AMDRevealCommand( + amount: 3, + name: 'Monsters', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Reveal 3 modifier cards'); + }); + }); +} diff --git a/server/test/command/bad_omen_command_test.dart b/server/test/command/bad_omen_command_test.dart new file mode 100644 index 0000000..1741099 --- /dev/null +++ b/server/test/command/bad_omen_command_test.dart @@ -0,0 +1,124 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/bad_omen_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_curse_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + // Setting a scenario resets the modifier decks to their default state. + final command = SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ); + command.execute(); + }); + + group('BadOmenCommand', () { + test('should increase badOmen value for monster deck', () { + // Arrange + final command = BadOmenCommand(false, gameState: getIt<GameState>()); + final monsterDeck = getIt<GameState>().modifierDeck; + final initialBadOmenValue = monsterDeck.badOmen; + + // Act + command.execute(); + + // Assert + expect(monsterDeck.badOmen, initialBadOmenValue + 6); + checkSaveState(); + }); + + test('should increase badOmen value for allies deck', () { + // Arrange + final command = BadOmenCommand(true, gameState: getIt<GameState>()); + final alliesDeck = getIt<GameState>().modifierDeckAllies; + final initialBadOmenValue = alliesDeck.badOmen; + + // Act + command.execute(); + + // Assert + expect(alliesDeck.badOmen, initialBadOmenValue + 6); + checkSaveState(); + }); + + test('should add curses on top', () { + // Arrange + final command = BadOmenCommand(false, gameState: getIt<GameState>()); + final monsterDeck = getIt<GameState>().modifierDeck; + final initialBadOmenValue = monsterDeck.badOmen; + + // Act + command.execute(); + + // Assert + expect(monsterDeck.badOmen, initialBadOmenValue + 6); + + ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + expect(monsterDeck.drawPileContents.toList()[15].gfx, "curse"); + expect(monsterDeck.badOmen, initialBadOmenValue + 5); + + ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + expect(monsterDeck.drawPileContents.toList()[15].gfx, "curse"); + expect(monsterDeck.badOmen, initialBadOmenValue + 4); + + ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + expect(monsterDeck.drawPileContents.toList()[15].gfx, "curse"); + expect(monsterDeck.badOmen, initialBadOmenValue + 3); + + ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + expect(monsterDeck.drawPileContents.toList()[15].gfx, "curse"); + expect(monsterDeck.badOmen, initialBadOmenValue + 2); + + ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + expect(monsterDeck.drawPileContents.toList()[15].gfx, "curse"); + expect(monsterDeck.badOmen, initialBadOmenValue + 1); + + checkSaveState(); + }); + + test('describe should return correct string', () { + // Arrange + final command = BadOmenCommand(false, gameState: getIt<GameState>()); + + // Act & Assert + expect(command.describe(), 'Bad Omen'); + }); + }); +} diff --git a/server/test/command/change_name_command_test.dart b/server/test/command/change_name_command_test.dart new file mode 100644 index 0000000..cb5dce4 --- /dev/null +++ b/server/test/command/change_name_command_test.dart @@ -0,0 +1,58 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/change_name_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + AddCharacterCommand('Blinkblade', 'Frosthaven', "Blinky", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('ChangeNameCommand', () { + test('should change a character\'s name', () { + // Arrange + final newName = 'BlinkyTheBlade'; + final command = ChangeNameCommand( + newName, + character.id, + gameState: getIt<GameState>(), + ); + final initialName = character.characterState.display; + expect(initialName, 'Blinky'); + + // Act + command.execute(); + + // Assert + final finalName = character.characterState.display; + expect(finalName, newName); + checkSaveState(); + }); + + test('describe should return correct string', () { + // Arrange + final command = ChangeNameCommand( + 'NewName', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Change character name'); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_bless_command_test.dart b/server/test/command/change_stat_commands/change_bless_command_test.dart new file mode 100644 index 0000000..9a9059e --- /dev/null +++ b/server/test/command/change_stat_commands/change_bless_command_test.dart @@ -0,0 +1,175 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_bless_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ); + }); + + group('ChangeBlessCommand', () { + test('should add a bless card to a character deck', () { + // Arrange + final character = getIt<GameState>().currentList.first as Character; + final command = ChangeBlessCommand( + 1, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + final initialBlessCount = character.characterState.modifierDeck + .getRemovable("bless"); + + // Act + command.execute(); + + // Assert + final finalBlessCount = character.characterState.modifierDeck + .getRemovable("bless"); + expect(finalBlessCount, initialBlessCount + 1); + checkSaveState(); + }); + + test('should remove a bless card from a character deck', () { + // Arrange + final character = getIt<GameState>().currentList.first as Character; + ChangeBlessCommand( + 1, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); // Add a bless first + final initialBlessCount = character.characterState.modifierDeck + .getRemovable("bless"); + final command = ChangeBlessCommand( + -1, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalBlessCount = character.characterState.modifierDeck + .getRemovable("bless"); + expect(finalBlessCount, initialBlessCount - 1); + checkSaveState(); + }); + + test('should add a bless card to the monster deck', () { + // Arrange + final gameState = getIt<GameState>(); + final command = ChangeBlessCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ); // Empty string for monster deck + final initialBlessCount = gameState.modifierDeck.getRemovable("bless"); + + // Act + command.execute(); + + // Assert + final finalBlessCount = gameState.modifierDeck.getRemovable("bless"); + expect(finalBlessCount, initialBlessCount + 1); + checkSaveState(); + }); + + test('should remove a bless card from the monster deck', () { + // Arrange + final gameState = getIt<GameState>(); + ChangeBlessCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a bless first + final initialBlessCount = gameState.modifierDeck.getRemovable("bless"); + final command = ChangeBlessCommand( + -1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalBlessCount = gameState.modifierDeck.getRemovable("bless"); + expect(finalBlessCount, initialBlessCount - 1); + checkSaveState(); + }); + + test('describe should return correct string for adding bless', () { + // Arrange + final command = ChangeBlessCommand( + 1, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add a Bless'); + checkSaveState(); + }); + + test('describe should return correct string for removing bless', () { + // Arrange + final command = ChangeBlessCommand( + -1, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Remove a Bless'); + checkSaveState(); + }); + + test('describe should return correct string for monster deck', () { + // Arrange + final command = ChangeBlessCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add a Bless'); + checkSaveState(); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_curse_command_test.dart b/server/test/command/change_stat_commands/change_curse_command_test.dart new file mode 100644 index 0000000..677181a --- /dev/null +++ b/server/test/command/change_stat_commands/change_curse_command_test.dart @@ -0,0 +1,175 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_curse_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ); + }); + + group('ChangeCurseCommand', () { + test('should add a curse card to a character deck', () { + // Arrange + final character = getIt<GameState>().currentList.first as Character; + final command = ChangeCurseCommand( + 1, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + final initialCurseCount = character.characterState.modifierDeck + .getRemovable("curse"); + + // Act + command.execute(); + + // Assert + final finalCurseCount = character.characterState.modifierDeck + .getRemovable("curse"); + expect(finalCurseCount, initialCurseCount + 1); + checkSaveState(); + }); + + test('should remove a curse card from a character deck', () { + // Arrange + final character = getIt<GameState>().currentList.first as Character; + ChangeCurseCommand( + 1, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + final initialCurseCount = character.characterState.modifierDeck + .getRemovable("curse"); + final command = ChangeCurseCommand( + -1, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCurseCount = character.characterState.modifierDeck + .getRemovable("curse"); + expect(finalCurseCount, initialCurseCount - 1); + checkSaveState(); + }); + + test('should add a curse card to the monster deck', () { + // Arrange + final gameState = getIt<GameState>(); + final command = ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ); // Empty string for monster deck + final initialCurseCount = gameState.modifierDeck.getRemovable("curse"); + + // Act + command.execute(); + + // Assert + final finalCurseCount = gameState.modifierDeck.getRemovable("curse"); + expect(finalCurseCount, initialCurseCount + 1); + checkSaveState(); + }); + + test('should remove a curse card from the monster deck', () { + // Arrange + final gameState = getIt<GameState>(); + ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ).execute(); // Add a curse first + final initialCurseCount = gameState.modifierDeck.getRemovable("curse"); + final command = ChangeCurseCommand( + -1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalCurseCount = gameState.modifierDeck.getRemovable("curse"); + expect(finalCurseCount, initialCurseCount - 1); + checkSaveState(); + }); + + test('describe should return correct string for adding curse', () { + // Arrange + final command = ChangeCurseCommand( + 1, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add a Curse'); + checkSaveState(); + }); + + test('describe should return correct string for removing curse', () { + // Arrange + final command = ChangeCurseCommand( + -1, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Remove a Curse'); + checkSaveState(); + }); + + test('describe should return correct string for monster deck', () { + // Arrange + final command = ChangeCurseCommand( + 1, + "Zealot", + "Zealot", + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add a Curse'); + checkSaveState(); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_empower_command_test.dart b/server/test/command/change_stat_commands/change_empower_command_test.dart new file mode 100644 index 0000000..53151e3 --- /dev/null +++ b/server/test/command/change_stat_commands/change_empower_command_test.dart @@ -0,0 +1,240 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_empower_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('ChangeEmpowerCommand', () { + test('should add an empowerment to a character', () { + // Arrange + final character = getIt<GameState>().currentList.first as Character; + final command = ChangeEmpowerCommand( + 1, + "in-empower", + character.id, + character.id, + gameState: getIt<GameState>(), + ); + final initialEmpowerCount = character.characterState.modifierDeck + .getRemovable("in-empower"); + + // Act + command.execute(); + + // Assert + final finalEmpowerCount = character.characterState.modifierDeck + .getRemovable("in-empower"); + expect(finalEmpowerCount, initialEmpowerCount + 1); + checkSaveState(); + }); + + test('should remove an empowerment from a character', () { + // Arrange + final character = getIt<GameState>().currentList.first as Character; + ChangeEmpowerCommand( + 1, + "in-empower", + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); // Add an empowerment first + final initialEmpowerCount = character.characterState.modifierDeck + .getRemovable("in-empower"); + final command = ChangeEmpowerCommand( + -1, + "in-empower", + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalEmpowerCount = character.characterState.modifierDeck + .getRemovable("in-empower"); + expect(finalEmpowerCount, initialEmpowerCount - 1); + checkSaveState(); + }); + + test('should add an empowerment to a monster instance', () { + // Arrange + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + final monsterInstance = monster.monsterInstances.first; + final command = ChangeEmpowerCommand( + 1, + "in-empower", + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ); + final initialEmpowerCount = getIt<GameState>().modifierDeck.getRemovable( + "in-empower", + ); + + // Act + command.execute(); + + // Assert + final finalEmpowerCount = getIt<GameState>().modifierDeck.getRemovable( + "in-empower", + ); + expect(finalEmpowerCount, initialEmpowerCount + 1); + checkSaveState(); + }); + + test('should remove an empowerment from a monster instance', () { + // Arrange + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + final monsterInstance = monster.monsterInstances.first; + ChangeEmpowerCommand( + 1, + "in-empower", + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ).execute(); // Add an empowerment first + final initialEmpowerCount = getIt<GameState>().modifierDeck.getRemovable( + "in-empower", + ); + final command = ChangeEmpowerCommand( + -1, + "in-empower", + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + final finalEmpowerCount = getIt<GameState>().modifierDeck.getRemovable( + "in-empower", + ); + expect(finalEmpowerCount, initialEmpowerCount - 1); + checkSaveState(); + }); + + test('describe should return correct string for adding empowerment', () { + // Arrange + final command = ChangeEmpowerCommand( + 1, + "in-empower", + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Add Empower'); + }); + + test('describe should return correct string for removing empowerment', () { + // Arrange + final command = ChangeEmpowerCommand( + -1, + "in-empower", + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Remove Empower'); + }); + + test('undo does not throw', () { + final gs = getIt<GameState>(); + final character = gs.currentList.first as Character; + gs.action( + ChangeEmpowerCommand( + 1, + "in-empower", + character.id, + character.id, + gameState: getIt<GameState>(), + ), + ); + expect(() => gs.undo(), returnsNormally); + }); + + test('.deck() named constructor targets the given deck directly', () { + final deck = getIt<GameState>().modifierDeck; + final before = deck.getRemovable("in-empower"); + ChangeEmpowerCommand.deck( + deck, + "in-empower", + gameState: getIt<GameState>(), + ).execute(); + // change defaults to 0 for .deck() constructor, so value unchanged + expect(deck.getRemovable("in-empower"), before); + }); + + test('ally monster owner uses modifierDeckAllies', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + // Rat Monstrosity is marked isAlly in #6 + final gs = getIt<GameState>(); + final ratMonstrosity = gs.currentList.whereType<Monster>().firstWhere( + (m) => m.id == 'Rat Monstrosity', + ); + expect(ratMonstrosity.isAlly, isTrue); + + final alliesDeckBefore = gs.modifierDeckAllies.getRemovable("in-empower"); + ChangeEmpowerCommand( + 1, + "in-empower", + ratMonstrosity.id, + ratMonstrosity.id, + gameState: getIt<GameState>(), + ).execute(); + expect( + gs.modifierDeckAllies.getRemovable("in-empower"), + alliesDeckBefore + 1, + ); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_enfeeble_command_test.dart b/server/test/command/change_stat_commands/change_enfeeble_command_test.dart new file mode 100644 index 0000000..9b10bed --- /dev/null +++ b/server/test/command/change_stat_commands/change_enfeeble_command_test.dart @@ -0,0 +1,145 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_enfeeble_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('ChangeEnfeebleCommand', () { + test('should add enfeeble to character modifier deck', () { + final character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + final initial = character.characterState.modifierDeck.getRemovable( + 'enfeeble', + ); + + ChangeEnfeebleCommand( + 1, + 'enfeeble', + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect( + character.characterState.modifierDeck.getRemovable('enfeeble'), + initial + 1, + ); + checkSaveState(); + }); + + test('should add enfeeble to monster modifier deck', () { + final gameState = getIt<GameState>(); + final initial = gameState.modifierDeck.getRemovable('enfeeble'); + + ChangeEnfeebleCommand( + 1, + 'enfeeble', + 'Ancient Artillery (FH)', + 'Ancient Artillery (FH)', + gameState: getIt<GameState>(), + ).execute(); + + expect(gameState.modifierDeck.getRemovable('enfeeble'), initial + 1); + }); + + test('describe should return "Add Enfeeble" when change is positive', () { + final command = ChangeEnfeebleCommand( + 1, + 'enfeeble', + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Add Enfeeble'); + }); + + test( + 'describe should return "Remove Enfeeble" when change is negative', + () { + final command = ChangeEnfeebleCommand( + -1, + 'enfeeble', + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Remove Enfeeble'); + }, + ); + + test('undo does not throw', () { + final gs = getIt<GameState>(); + final character = gs.currentList.first as Character; + gs.action( + ChangeEnfeebleCommand( + 1, + 'enfeeble', + character.id, + character.id, + gameState: getIt<GameState>(), + ), + ); + expect(() => gs.undo(), returnsNormally); + }); + + test('.deck() named constructor targets the given deck directly', () { + final deck = getIt<GameState>().modifierDeck; + final before = deck.getRemovable('enfeeble'); + ChangeEnfeebleCommand.deck( + deck, + 'enfeeble', + gameState: getIt<GameState>(), + ).execute(); + // change defaults to 0 for .deck() constructor, so value unchanged + expect(deck.getRemovable('enfeeble'), before); + }); + + test('ally monster owner uses modifierDeckAllies', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final gs = getIt<GameState>(); + final ratMonstrosity = gs.currentList.whereType<Monster>().firstWhere( + (m) => m.id == 'Rat Monstrosity', + ); + expect(ratMonstrosity.isAlly, isTrue); + + final before = gs.modifierDeckAllies.getRemovable('enfeeble'); + ChangeEnfeebleCommand( + 1, + 'enfeeble', + ratMonstrosity.id, + ratMonstrosity.id, + gameState: getIt<GameState>(), + ).execute(); + expect(gs.modifierDeckAllies.getRemovable('enfeeble'), before + 1); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_health_command_test.dart b/server/test/command/change_stat_commands/change_health_command_test.dart new file mode 100644 index 0000000..159ad74 --- /dev/null +++ b/server/test/command/change_stat_commands/change_health_command_test.dart @@ -0,0 +1,193 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + group('ChangeHealthCommand', () { + test('should increase a character\'s health', () { + // Arrange + final initialHealth = character.characterState.health; + final command = ChangeHealthCommand( + 5, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.health, initialHealth + 5); + }); + + test('should decrease a character\'s health', () { + // Arrange + final initialHealth = character.characterState.health; + final command = ChangeHealthCommand( + -5, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.health, initialHealth - 5); + }); + + test('should kill a character when health reaches 0', () { + // Arrange + final command = ChangeHealthCommand( + -100, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.health, 0); + // A killed character's turn should be marked as done. this is not true + //expect(character.turnState, TurnsState.done); + }); + + test('should increase a monster instance\'s health', () { + // Arrange + final initialHealth = monsterInstance.health; + final command = ChangeHealthCommand( + 3, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(monsterInstance.health, initialHealth + 3); + }); + + test('should kill a monster instance when health reaches 0', () { + // Arrange + final command = ChangeHealthCommand( + -100, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + final initialInstanceCount = monster.monsterInstances.length; + + // Act + command.execute(); + + // Assert + expect(monster.monsterInstances.length, initialInstanceCount - 1); + }); + + test('should not decrease health below 0', () { + // Arrange + final command = ChangeHealthCommand( + -100, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.health, 0); + }); + + test('describe should return correct string for increasing health', () { + final command = ChangeHealthCommand( + 5, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Increase Blinkblade's health by 5"); + }); + + test('describe should return correct string for decreasing health', () { + final command = ChangeHealthCommand( + -5, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Decrease Blinkblade's health by 5"); + }); + + test('describe should return kill string if health is already 0', () { + // Arrange + //character.characterState.setHealth(StateModifier(), 0); + ChangeHealthCommand( + -100, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + final command = ChangeHealthCommand( + -1, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act & Assert + expect(command.describe(), 'Kill Blinkblade'); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_max_health_command_test.dart b/server/test/command/change_stat_commands/change_max_health_command_test.dart new file mode 100644 index 0000000..a07006d --- /dev/null +++ b/server/test/command/change_stat_commands/change_max_health_command_test.dart @@ -0,0 +1,183 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_max_health_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + group('ChangeMaxHealthCommand', () { + test('should increase a character\'s max health', () { + // Arrange + final initialMaxHealth = character.characterState.maxHealth; + final command = ChangeMaxHealthCommand( + 5, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.maxHealth, initialMaxHealth + 5); + }); + + test('should decrease a character\'s max health', () { + // Arrange + final initialMaxHealth = character.characterState.maxHealth; + final command = ChangeMaxHealthCommand( + -2, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.maxHealth, initialMaxHealth - 2); + }); + + test('should lower current health if it exceeds new max health', () { + // Arrange + final initialHealth = character.characterState.health; + expect(initialHealth, equals(character.characterState.maxHealth)); + final command = ChangeMaxHealthCommand( + -3, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect( + character.characterState.health, + character.characterState.maxHealth, + ); + }); + + test( + 'should update current health when max health changes if they were equal', + () { + // Arrange + final command = ChangeMaxHealthCommand( + 5, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + final initialHealth = character.characterState.health; + final initialMaxHealth = character.characterState.maxHealth; + expect(initialHealth, initialMaxHealth); + + // Act + command.execute(); + + // Assert + expect(character.characterState.health, initialHealth + 5); + expect(character.characterState.maxHealth, initialMaxHealth + 5); + }, + ); + + test('should not set max health to 0 or below', () { + // Arrange + final initialMaxHealth = character.characterState.maxHealth; + final command = ChangeMaxHealthCommand( + -100, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.maxHealth, initialMaxHealth); + }); + + test('should increase a monster instance\'s max health', () { + // Arrange + final initialMaxHealth = monsterInstance.maxHealth; + final command = ChangeMaxHealthCommand( + 3, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(monsterInstance.maxHealth, initialMaxHealth + 3); + }); + + test('describe should return correct string for increasing max health', () { + final command = ChangeMaxHealthCommand( + 5, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Increase Blinkblade's max health"); + }); + + test('describe should return correct string for decreasing max health', () { + final command = ChangeMaxHealthCommand( + -5, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Decrease Blinkblade's max health"); + }); + }); +} diff --git a/server/test/command/change_stat_commands/change_stat_command_test.dart b/server/test/command/change_stat_commands/change_stat_command_test.dart new file mode 100644 index 0000000..5efba06 --- /dev/null +++ b/server/test/command/change_stat_commands/change_stat_command_test.dart @@ -0,0 +1,294 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/next_round_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + // ChangeStatCommand is abstract; tested through ChangeHealthCommand as a concrete example + group('ChangeStatCommand (via ChangeHealthCommand)', () { + test('handleDeath removes monster instance when health reaches 0', () { + final currentHp = monsterInstance.health; + // Deal lethal damage + ChangeHealthCommand( + -currentHp, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(monster.monsterInstances, isEmpty); + }); + + test('handleDeath keeps character in list when health reaches 0', () { + final currentHp = character.characterState.health; + ChangeHealthCommand( + -currentHp, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(getIt<GameState>().currentList.contains(character), isTrue); + }); + + test('describe returns "change stat"', () { + // ChangeStatCommand.describe() returns "change stat" + final command = ChangeHealthCommand( + 1, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + // ChangeHealthCommand overrides describe, so check base via setChange + command.setChange(0); + expect(command.describe(), isNotEmpty); + }); + + test('handleDeath: monster death in playTurns state does not throw', () { + // Enter playTurns state + DrawCommand(gameState: getIt<GameState>()).execute(); + expect(getIt<GameState>().roundState, RoundState.playTurns); + final currentHp = monsterInstance.health; + // Kill the monster standee while in playTurns + expect( + () => ChangeHealthCommand( + -currentHp, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(), + returnsNormally, + ); + expect(monster.monsterInstances, isEmpty); + }); + + test( + 'handleDeath: character un-death triggers update (health 0 → positive)', + () { + // Kill the character + final maxHp = character.characterState.health; + ChangeHealthCommand( + -maxHp, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + expect(character.characterState.health, 0); + // Revive: going from 0 to positive triggers the un-death path (line 23) + expect( + () => ChangeHealthCommand( + 1, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(), + returnsNormally, + ); + expect(character.characterState.health, 1); + }, + ); + + test( + 'handleDeath: summon death removes summon from character summonList', + () { + // Add Banner Spear (has summons in test data) + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', null, 1).execute(); + final gs = getIt<GameState>(); + final bannerSpear = + gs.currentList.firstWhere((e) => e is Character) as Character; + + // Add a summon with health=1 so it dies on 1 damage + final summonData = SummonData( + 1, + 'BAN reinforcements', + 1, + 2, + 0, + 0, + 'BAN reinforcements', + ); + AddStandeeCommand( + 1, + summonData, + bannerSpear.id, + MonsterType.summon, + true, + gameState: getIt<GameState>(), + ).execute(); + + expect(bannerSpear.characterState.summonList, isNotEmpty); + final summonId = bannerSpear.characterState.summonList.first.getId(); + + // Kill the summon using its full ID (name+gfx+standeeNr) + ChangeHealthCommand( + -1, + summonId, + bannerSpear.id, + gameState: getIt<GameState>(), + ).execute(); + + // Summon should be removed + expect(bannerSpear.characterState.summonList, isEmpty); + }, + ); + + test('handleDeath: summon death in playTurns state does not throw', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', null, 1).execute(); + final gs = getIt<GameState>(); + final bannerSpear = + gs.currentList.firstWhere((e) => e is Character) as Character; + + final summonData = SummonData( + 1, + 'BAN reinforcements', + 1, + 2, + 0, + 0, + 'BAN reinforcements', + ); + AddStandeeCommand( + 1, + summonData, + bannerSpear.id, + MonsterType.summon, + true, + gameState: getIt<GameState>(), + ).execute(); + final summonId = bannerSpear.characterState.summonList.first.getId(); + + // Enter playTurns state + DrawCommand(gameState: getIt<GameState>()).execute(); + expect(gs.roundState, RoundState.playTurns); + + // Kill summon in playTurns + expect( + () => ChangeHealthCommand( + -1, + summonId, + bannerSpear.id, + gameState: getIt<GameState>(), + ).execute(), + returnsNormally, + ); + expect(bannerSpear.characterState.summonList, isEmpty); + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + }); + + test( + 'handleDeath: summon death when more summons remain still updates', + () { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', null, 1).execute(); + final gs = getIt<GameState>(); + final bannerSpear = + gs.currentList.firstWhere((e) => e is Character) as Character; + + // Add two summons with health 1 and 2 + final summonData1 = SummonData( + 1, + 'BAN reinforcements', + 1, + 2, + 0, + 0, + 'BAN reinforcements', + ); + final summonData2 = SummonData( + 2, + 'BAN banner of strength', + 2, + 2, + 0, + 0, + 'BAN banner of strength', + ); + AddStandeeCommand( + 1, + summonData1, + bannerSpear.id, + MonsterType.summon, + true, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 2, + summonData2, + bannerSpear.id, + MonsterType.summon, + true, + gameState: getIt<GameState>(), + ).execute(); + + expect(bannerSpear.characterState.summonList.length, 2); + // Get the ID of the first summon (health=1) before it's removed + final firstSummonId = bannerSpear.characterState.summonList + .firstWhere((s) => s.standeeNr == 1) + .getId(); + + // Kill only the first summon (health 1 → 0) + ChangeHealthCommand( + -1, + firstSummonId, + bannerSpear.id, + gameState: getIt<GameState>(), + ).execute(); + + // One summon remains + expect(bannerSpear.characterState.summonList.length, 1); + }, + ); + }); +} diff --git a/server/test/command/change_stat_commands/change_xp_command_test.dart b/server/test/command/change_stat_commands/change_xp_command_test.dart new file mode 100644 index 0000000..a782abc --- /dev/null +++ b/server/test/command/change_stat_commands/change_xp_command_test.dart @@ -0,0 +1,103 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_xp_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('ChangeXPCommand', () { + test('should increase a character\'s XP', () { + // Arrange + final initialXp = character.characterState.xp; + final command = ChangeXPCommand( + 10, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.xp, initialXp + 10); + }); + + test('should decrease a character\'s XP', () { + // Arrange + ChangeXPCommand( + 20, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + final initialXp = character.characterState.xp; + final command = ChangeXPCommand( + -5, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.xp, initialXp - 5); + }); + + test('should not decrease XP below 0', () { + // Arrange + final command = ChangeXPCommand( + -100, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + + // Act + command.execute(); + + // Assert + expect(character.characterState.xp, 0); + }); + + test('describe should return correct string for increasing XP', () { + final command = ChangeXPCommand( + 10, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Increase Blinkblade's xp by 10"); + }); + + test('describe should return correct string for decreasing XP', () { + final command = ChangeXPCommand( + -5, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Decrease Blinkblade's xp by 5"); + }); + }); +} diff --git a/server/test/command/clear_unlocked_classes_command_test.dart b/server/test/command/clear_unlocked_classes_command_test.dart new file mode 100644 index 0000000..fcb47a5 --- /dev/null +++ b/server/test/command/clear_unlocked_classes_command_test.dart @@ -0,0 +1,52 @@ +// ignore_for_file: no-empty-block + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/clear_unlocked_classes_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() {}); + + group('ClearUnlockedClassesCommand', () { + test('should clear unlocked classes', () { + // Arrange + AddCharacterCommand( + "Banner Spear", + "Frosthaven", + "Banny", + 1, + ).execute(); //test data BS is hidden class + + final gameState = getIt<GameState>(); + expect( + gameState.unlockedClasses, + isNotEmpty, + reason: "Prerequisite: A class should be unlocked.", + ); + + final command = ClearUnlockedClassesCommand(); + + // Act + command.execute(); + + // Assert + expect(gameState.unlockedClasses, isEmpty); + }); + + test('describe should return correct string', () { + // Arrange + final command = ClearUnlockedClassesCommand(); + + // Act & Assert + expect(command.describe(), 'Clear unlocked classes'); + }); + }); +} diff --git a/server/test/command/command_registry_test.dart b/server/test/command/command_registry_test.dart new file mode 100644 index 0000000..25f4d10 --- /dev/null +++ b/server/test/command/command_registry_test.dart @@ -0,0 +1,144 @@ +// ignore_for_file: avoid-top-level-members-in-tests + +import 'package:test/test.dart'; + +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_condition_command.dart'; +import 'package:x_haven_server/core/commands/command_registry.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import 'test_helpers.dart'; + +void _tests() { + group('command registry', () { + test('unknown name throws CommandRegistryError', () { + expect( + () => buildCommand('noSuchCommand', const {}, gameState), + throwsA( + isA<CommandRegistryError>().having( + (e) => e.message, + 'message', + contains('noSuchCommand'), + ), + ), + ); + }); + + test('addCharacter builds and executes', () { + final command = buildCommand('addCharacter', { + 'id': 'Blinkblade', + 'edition': 'Frosthaven', + 'display': '', + 'level': 1, + }, gameState); + expect(command, isA<AddCharacterCommand>()); + expect(commandName(command), 'addCharacter'); + command.execute(); + expect(gameState.currentList.length, 1); + expect(gameState.currentList.single, isA<Character>()); + }); + + test('command constructor failure is wrapped as CommandRegistryError', () { + expect( + () => buildCommand('addCharacter', { + 'id': 'NotACharacter', + 'edition': 'Frosthaven', + 'display': '', + 'level': 1, + }, gameState), + throwsA( + isA<CommandRegistryError>().having( + (e) => e.message, + 'message', + contains('NotACharacter'), + ), + ), + ); + }); + + test('missing required arg throws with the arg name in the message', () { + expect( + () => buildCommand('addCondition', {'condition': 'chill'}, gameState), + throwsA( + isA<CommandRegistryError>().having( + (e) => e.message, + 'message', + contains('figureId'), + ), + ), + ); + }); + + test('wrong arg type throws', () { + expect( + () => buildCommand('setInit', { + 'characterId': 'Blinkblade', + 'init': '3', + }, gameState), + throwsA( + isA<CommandRegistryError>().having( + (e) => e.message, + 'message', + contains('init'), + ), + ), + ); + }); + + test('enum args are resolved by name', () { + final command = buildCommand('addCondition', { + 'condition': 'chill', + 'figureId': 'Blinkblade', + }, gameState); + expect(command, isA<AddConditionCommand>()); + expect((command as AddConditionCommand).condition, Condition.chill); + expect(commandName(command), 'addCondition'); + }); + + test('bogus enum value throws', () { + expect( + () => buildCommand('addCondition', { + 'condition': 'notACondition', + 'figureId': 'Blinkblade', + }, gameState), + throwsA( + isA<CommandRegistryError>().having( + (e) => e.message, + 'message', + contains('notACondition'), + ), + ), + ); + }); + + test('commandName round-trips for other commands', () { + final built = <MapEntry<String, Command>>[ + MapEntry('draw', buildCommand('draw', const {}, gameState)), + MapEntry( + 'drawLootCard', + buildCommand('drawLootCard', const {}, gameState), + ), + MapEntry( + 'changeHealth', + buildCommand('changeHealth', { + 'change': -1, + 'figureId': 'Blinkblade', + }, gameState), + ), + MapEntry( + 'useElement', + buildCommand('useElement', {'element': 'fire'}, gameState), + ), + ]; + for (final entry in built) { + expect(commandName(entry.value), entry.key); + } + }); + }); +} + +Future<void> main() async { + await setUpGame(); + _tests(); +} diff --git a/server/test/command/corrosive_spew_command_test.dart b/server/test/command/corrosive_spew_command_test.dart new file mode 100644 index 0000000..d47acf8 --- /dev/null +++ b/server/test/command/corrosive_spew_command_test.dart @@ -0,0 +1,31 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/corrosive_spew_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('CorrosiveSpewCommand', () { + test('should set corrosiveSpew to true on main modifier deck', () { + // CorrosiveSpew targets "Ruinmaw" which falls through to the main deck + expect(getIt<GameState>().modifierDeck.corrosiveSpew, isFalse); + + CorrosiveSpewCommand(gameState: getIt<GameState>()).execute(); + + expect(getIt<GameState>().modifierDeck.corrosiveSpew, isTrue); + checkSaveState(); + }); + + test('describe returns correct string', () { + expect( + CorrosiveSpewCommand(gameState: getIt<GameState>()).describe(), + 'Corrosive Spew', + ); + }); + }); +} diff --git a/server/test/command/donate_cs_sanctuary_command_test.dart b/server/test/command/donate_cs_sanctuary_command_test.dart new file mode 100644 index 0000000..c23357e --- /dev/null +++ b/server/test/command/donate_cs_sanctuary_command_test.dart @@ -0,0 +1,77 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/donate_cs_sanctuary_command.dart'; +import 'package:x_haven_server/core/commands/remove_cs_sanctuary_donation_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('DonateCSSanctuaryCommand', () { + test('should add sanctuary cards to character modifier deck', () { + final deck = character.characterState.modifierDeck; + final countBefore = deck.drawPileSize; + + DonateCSSanctuaryCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.hasCSSanctuary(), isTrue); + expect(deck.drawPileSize, greaterThan(countBefore)); + checkSaveState(); + }); + + test('describe includes character id', () { + final command = DonateCSSanctuaryCommand( + character.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), '${character.id} donate to sanctuary'); + }); + }); + + group('RemoveCSSanctuaryDonationCommand', () { + test('should remove sanctuary cards from character modifier deck', () { + DonateCSSanctuaryCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); + final deck = character.characterState.modifierDeck; + expect(deck.hasCSSanctuary(), isTrue); + + RemoveCSSanctuaryDonationCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.hasCSSanctuary(), isFalse); + checkSaveState(); + }); + + test('describe includes character id', () { + final command = RemoveCSSanctuaryDonationCommand( + character.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), "Remove ${character.id}'s donation"); + }); + }); +} diff --git a/server/test/command/draw_ability_card_command_test.dart b/server/test/command/draw_ability_card_command_test.dart new file mode 100644 index 0000000..4c73d08 --- /dev/null +++ b/server/test/command/draw_ability_card_command_test.dart @@ -0,0 +1,51 @@ +// ignore_for_file: avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/draw_ability_card_command.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('DrawAbilityCardCommand', () { + test('should move a card from draw pile to discard pile', () { + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + final deck = GameMethods.getDeck(monster.type.deck)!; + final drawBefore = deck.drawPileSize; + final discardBefore = deck.discardPileSize; + + DrawAbilityCardCommand(monster.id).execute(); + + expect(deck.drawPileSize, drawBefore - 1); + expect(deck.discardPileSize, discardBefore + 1); + checkSaveState(); + }); + + test('describe returns correct string', () { + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + final command = DrawAbilityCardCommand(monster.id); + expect(command.describe(), 'Draw extra ability card'); + }); + }); +} diff --git a/server/test/command/draw_command_test.dart b/server/test/command/draw_command_test.dart new file mode 100644 index 0000000..2e14e71 --- /dev/null +++ b/server/test/command/draw_command_test.dart @@ -0,0 +1,46 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'Blinky', 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('DrawCommand', () { + test('should set round state to playTurns', () { + DrawCommand(gameState: getIt<GameState>()).execute(); + expect(getIt<GameState>().roundState, RoundState.playTurns); + checkSaveState(); + }); + + test('should set first list item turn state to current', () { + DrawCommand(gameState: getIt<GameState>()).execute(); + expect( + getIt<GameState>().currentList.first.turnState, + TurnsState.current, + ); + }); + + test('describe returns "Draw"', () { + expect(DrawCommand(gameState: getIt<GameState>()).describe(), 'Draw'); + }); + }); +} diff --git a/server/test/command/draw_loot_card_command_test.dart b/server/test/command/draw_loot_card_command_test.dart new file mode 100644 index 0000000..80abe4c --- /dev/null +++ b/server/test/command/draw_loot_card_command_test.dart @@ -0,0 +1,87 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/draw_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/return_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + // Frosthaven custom scenario creates a loot deck + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('DrawLootCardCommand', () { + test('should move a card from draw pile to discard pile', () { + final lootDeck = getIt<GameState>().lootDeck; + expect( + lootDeck.drawPileIsNotEmpty, + isTrue, + reason: 'Frosthaven custom scenario should have a loot deck', + ); + final drawBefore = lootDeck.drawPileSize; + final discardBefore = lootDeck.discardPileSize; + + DrawLootCardCommand(gameState: getIt<GameState>()).execute(); + + expect(lootDeck.drawPileSize, drawBefore - 1); + expect(lootDeck.discardPileSize, discardBefore + 1); + checkSaveState(); + }); + + test('should do nothing when draw pile is empty', () { + final lootDeck = getIt<GameState>().lootDeck; + final totalCards = lootDeck.drawPileSize + lootDeck.discardPileSize; + // Drain draw pile + while (lootDeck.drawPileIsNotEmpty) { + DrawLootCardCommand(gameState: getIt<GameState>()).execute(); + } + DrawLootCardCommand( + gameState: getIt<GameState>(), + ).execute(); // should not throw + expect(lootDeck.drawPileSize + lootDeck.discardPileSize, totalCards); + }); + + test('describe returns correct string', () { + expect( + DrawLootCardCommand(gameState: getIt<GameState>()).describe(), + 'Draw loot card', + ); + }); + }); + + group('ReturnLootCardCommand', () { + test('should return discard card to top of draw pile', () { + DrawLootCardCommand(gameState: getIt<GameState>()).execute(); + final lootDeck = getIt<GameState>().lootDeck; + final drawBefore = lootDeck.drawPileSize; + final discardBefore = lootDeck.discardPileSize; + + ReturnLootCardCommand(true, gameState: getIt<GameState>()).execute(); + + expect(lootDeck.drawPileSize, drawBefore + 1); + expect(lootDeck.discardPileSize, discardBefore - 1); + checkSaveState(); + }); + + test('describe returns correct string', () { + expect( + ReturnLootCardCommand(true, gameState: getIt<GameState>()).describe(), + 'Return loot card', + ); + }); + }); +} diff --git a/server/test/command/draw_modifier_card_command_test.dart b/server/test/command/draw_modifier_card_command_test.dart new file mode 100644 index 0000000..ebb4bd7 --- /dev/null +++ b/server/test/command/draw_modifier_card_command_test.dart @@ -0,0 +1,42 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('DrawModifierCardCommand', () { + test('should move a card from draw pile to discard pile', () { + final deck = getIt<GameState>().modifierDeck; + final drawBefore = deck.drawPileSize; + final discardBefore = deck.discardPileSize; + + DrawModifierCardCommand('', gameState: getIt<GameState>()).execute(); + + expect(deck.drawPileSize, drawBefore - 1); + expect(deck.discardPileSize, discardBefore + 1); + checkSaveState(); + }); + + test('describe with empty name returns monster string', () { + final command = DrawModifierCardCommand( + '', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Draw monster modifier card'); + }); + + test('describe with non-empty name includes name', () { + final command = DrawModifierCardCommand( + 'Blinkblade', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Draw Blinkblade modifier card'); + }); + }); +} diff --git a/server/test/command/enhance_loot_card_command_test.dart b/server/test/command/enhance_loot_card_command_test.dart new file mode 100644 index 0000000..73ebc3b --- /dev/null +++ b/server/test/command/enhance_loot_card_command_test.dart @@ -0,0 +1,82 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/enhance_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('EnhanceLootCardCommand', () { + test('should add an enhancement to a loot card', () { + final lootDeck = getIt<GameState>().lootDeck; + // Get any existing card id from the draw pile + if (lootDeck.drawPileIsNotEmpty) { + final cardId = lootDeck.drawPileContents.toList().first.id; + + EnhanceLootCardCommand( + cardId, + 2, + 'coin', + gameState: getIt<GameState>(), + ).execute(); + + // After enhancement the deck is rebuilt; verify it doesn't crash + expect(lootDeck.drawPileIsNotEmpty, isTrue); + checkSaveState(); + } + }); + + test('describe returns "Add Loot Enhancement" when value is positive', () { + expect( + EnhanceLootCardCommand( + 1, + 1, + 'coin', + gameState: getIt<GameState>(), + ).describe(), + 'Add Loot Enhancement', + ); + }); + + test( + 'describe returns "Remove Loot Enhancement" when value is zero or negative', + () { + expect( + EnhanceLootCardCommand( + 1, + 0, + 'coin', + gameState: getIt<GameState>(), + ).describe(), + 'Remove Loot Enhancement', + ); + expect( + EnhanceLootCardCommand( + 1, + -1, + 'coin', + gameState: getIt<GameState>(), + ).describe(), + 'Remove Loot Enhancement', + ); + }, + ); + }); +} diff --git a/server/test/command/ice_wraith_change_form_command_test.dart b/server/test/command/ice_wraith_change_form_command_test.dart new file mode 100644 index 0000000..bbdc31f --- /dev/null +++ b/server/test/command/ice_wraith_change_form_command_test.dart @@ -0,0 +1,97 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/ice_wraith_change_form_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + group('IceWraithChangeFormCommand', () { + test('should change type to elite when isElite is false', () { + expect(monsterInstance.type, MonsterType.normal); + + IceWraithChangeFormCommand( + false, + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ).execute(); + + expect(monsterInstance.type, MonsterType.elite); + }); + + test('should change type to normal when isElite is true', () { + // First set to elite + IceWraithChangeFormCommand( + false, + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ).execute(); + expect(monsterInstance.type, MonsterType.elite); + + IceWraithChangeFormCommand( + true, + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ).execute(); + + expect(monsterInstance.type, MonsterType.normal); + }); + + test('describe when isElite is false returns turn-normal string', () { + final command = IceWraithChangeFormCommand( + false, + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Ice Wraith turn normal'); + }); + + test('describe when isElite is true returns turn-elite string', () { + final command = IceWraithChangeFormCommand( + true, + monster.id, + monsterInstance.getId(), + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Ice Wraith turn elite'); + }); + }); +} diff --git a/server/test/command/imbue_element_command_test.dart b/server/test/command/imbue_element_command_test.dart new file mode 100644 index 0000000..564e0c6 --- /dev/null +++ b/server/test/command/imbue_element_command_test.dart @@ -0,0 +1,44 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/imbue_element_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('ImbueElementCommand', () { + test('should set element to full when half is false', () { + final command = ImbueElementCommand(Elements.fire, false); + command.execute(); + expect(getIt<GameState>().elementState[Elements.fire], ElementState.full); + checkSaveState(); + }); + + test('should set element to half when half is true', () { + final command = ImbueElementCommand(Elements.light, true); + command.execute(); + expect( + getIt<GameState>().elementState[Elements.light], + ElementState.half, + ); + checkSaveState(); + }); + + test('should work on all element types', () { + for (final element in Elements.values) { + ImbueElementCommand(element, false).execute(); + expect(getIt<GameState>().elementState[element], ElementState.full); + } + }); + + test('describe should include element name', () { + final command = ImbueElementCommand(Elements.dark, false); + expect(command.describe(), 'Imbue element dark'); + }); + }); +} diff --git a/server/test/command/load_save_command_test.dart b/server/test/command/load_save_command_test.dart new file mode 100644 index 0000000..2715913 --- /dev/null +++ b/server/test/command/load_save_command_test.dart @@ -0,0 +1,96 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/load_character_save_command.dart'; +import 'package:x_haven_server/core/commands/load_save_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('LoadSaveCommand', () { + test('should restore game state from serialized data', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'SaveTest', 1).execute(); + final savedData = getIt<GameState>().toString(); + + // Change state + getIt<GameState>().clearList(); + + // Restore + LoadSaveCommand( + 'test save', + savedData, + gameState: getIt<GameState>(), + ).execute(); + + expect(getIt<GameState>().currentList.whereType<Character>().length, 1); + expect( + getIt<GameState>().currentList + .whereType<Character>() + .first + .characterState + .display, + 'SaveTest', + ); + }); + + test('describe includes save name', () { + final command = LoadSaveCommand( + 'my save', + '{}', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Load saved game: my save'); + }); + }); + + group('LoadCharacterSaveCommand', () { + test('should load a character from serialized character data', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'OrigName', 1).execute(); + final character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + final charData = character.toSave(); + + // Remove the character + getIt<GameState>().clearList(); + + // Reload from save data + LoadCharacterSaveCommand( + 'Blinkblade', + charData, + gameState: getIt<GameState>(), + ).execute(); + + final loaded = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + expect(loaded.id, 'Blinkblade'); + expect(loaded.characterState.display, 'OrigName'); + }); + + test('describe includes save name', () { + final command = LoadCharacterSaveCommand( + 'Blinkblade', + '{}', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Load saved character: Blinkblade'); + }); + }); +} diff --git a/server/test/command/mutable_game_methods_test.dart b/server/test/command/mutable_game_methods_test.dart new file mode 100644 index 0000000..cf678c2 --- /dev/null +++ b/server/test/command/mutable_game_methods_test.dart @@ -0,0 +1,1488 @@ +// ignore_for_file: avoid-late-keyword, no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_condition_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_perk_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/commands/draw_ability_card_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/imbue_element_command.dart'; +import 'package:x_haven_server/core/commands/next_round_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_character_level_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/commands/turn_done_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + // --------------------------------------------------------------------------- + // sortByInitiative (called by DrawCommand) + // --------------------------------------------------------------------------- + group('sortByInitiative via DrawCommand', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + }); + + test( + 'character with lower initiative is placed before character with higher initiative', + () { + SetInitCommand( + 'Blinkblade', + 10, + gameState: getIt<GameState>(), + ).execute(); + SetInitCommand( + 'Banner Spear', + 30, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + + final list = getIt<GameState>().currentList; + final bbIdx = list.indexWhere((e) => e.id == 'Blinkblade'); + final bsIdx = list.indexWhere((e) => e.id == 'Banner Spear'); + expect( + bbIdx, + lessThan(bsIdx), + reason: + 'Blinkblade (init 10) should come before Banner Spear (init 30)', + ); + }, + ); + + test( + 'character with higher initiative is placed after character with lower initiative', + () { + SetInitCommand( + 'Blinkblade', + 40, + gameState: getIt<GameState>(), + ).execute(); + SetInitCommand( + 'Banner Spear', + 15, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + + final list = getIt<GameState>().currentList; + final bbIdx = list.indexWhere((e) => e.id == 'Blinkblade'); + final bsIdx = list.indexWhere((e) => e.id == 'Banner Spear'); + expect( + bsIdx, + lessThan(bbIdx), + reason: + 'Banner Spear (init 15) should come before Blinkblade (init 40)', + ); + }, + ); + + test( + 'dead character (health=0) is sorted after alive character even with lower initiative', + () { + final gs = getIt<GameState>(); + final bs = + gs.currentList.firstWhere( + (e) => e is Character && e.id == 'Banner Spear', + ) + as Character; + ChangeHealthCommand( + -bs.characterState.health, + bs.id, + bs.id, + gameState: getIt<GameState>(), + ).execute(); + expect(bs.characterState.health, 0); + + // Banner Spear has lower initiative but is dead + SetInitCommand( + 'Blinkblade', + 30, + gameState: getIt<GameState>(), + ).execute(); + SetInitCommand( + 'Banner Spear', + 5, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + + final list = gs.currentList; + final bbIdx = list.indexWhere((e) => e.id == 'Blinkblade'); + final bsIdx = list.indexWhere((e) => e.id == 'Banner Spear'); + expect( + bbIdx, + lessThan(bsIdx), + reason: + 'Dead Banner Spear should be last even with initiative 5 vs 30', + ); + }, + ); + + test('inactive monster sorted after active character', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + + SetInitCommand('Blinkblade', 50, gameState: getIt<GameState>()).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + + final list = getIt<GameState>().currentList; + final charIdx = list.indexWhere((e) => e is Character); + final monsterIdx = list.indexWhere((e) => e is Monster); + expect( + charIdx, + lessThan(monsterIdx), + reason: 'Character should come before inactive monster', + ); + }); + + test( + 'active monster sorted by drawn ability card initiative relative to character', + () { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + + final zealot = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Zealot', + ) + as Monster; + AddStandeeCommand( + 1, + null, + zealot.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + // Character initiative very high so Zealot should normally come first + SetInitCommand( + 'Blinkblade', + 99, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + + final zealotDeck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == zealot.type.deck, + ); + final zealotInit = zealotDeck.discardPileTop.initiative; + + final list = getIt<GameState>().currentList; + final zealotIdx = list.indexWhere((e) => e.id == 'Zealot'); + final charIdx = list.indexWhere( + (e) => e is Character && e.id == 'Blinkblade', + ); + + if (zealotInit < 99) { + expect( + zealotIdx, + lessThan(charIdx), + reason: + 'Zealot (init $zealotInit) should precede Blinkblade (init 99)', + ); + } else { + expect( + charIdx, + lessThan(zealotIdx), + reason: + 'Blinkblade (init 99) should precede Zealot (init $zealotInit)', + ); + } + }, + ); + }); + + // --------------------------------------------------------------------------- + // sortMonsterInstances (called during AddStandeeCommand) + // --------------------------------------------------------------------------- + group('sortMonsterInstances', () { + late Monster monster; + + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + }); + + test('elite standee is sorted before normal standee', () { + AddStandeeCommand( + 2, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.elite, + false, + gameState: getIt<GameState>(), + ).execute(); + + final instances = monster.monsterInstances; + expect( + instances[0].type, + MonsterType.elite, + reason: 'Elite should be first in the instance list', + ); + expect( + instances[1].type, + MonsterType.normal, + reason: 'Normal should be second', + ); + }); + + test('normal standees are sorted by standee number ascending', () { + AddStandeeCommand( + 3, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + final instances = monster.monsterInstances; + expect( + instances[0].standeeNr, + 1, + reason: 'Lower standee number should come first', + ); + expect(instances[1].standeeNr, 3); + }); + + test('elite standees are sorted by standee number ascending', () { + AddStandeeCommand( + 3, + null, + monster.id, + MonsterType.elite, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.elite, + false, + gameState: getIt<GameState>(), + ).execute(); + + final instances = monster.monsterInstances; + expect(instances[0].standeeNr, 1); + expect(instances[1].standeeNr, 3); + }); + + test('mixed: elites by nr come before normals by nr', () { + AddStandeeCommand( + 2, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 3, + null, + monster.id, + MonsterType.elite, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.elite, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 4, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + final instances = monster.monsterInstances; + expect(instances[0].type, MonsterType.elite); + expect(instances[0].standeeNr, 1); + expect(instances[1].type, MonsterType.elite); + expect(instances[1].standeeNr, 3); + expect(instances[2].type, MonsterType.normal); + expect(instances[2].standeeNr, 2); + expect(instances[3].type, MonsterType.normal); + expect(instances[3].standeeNr, 4); + }); + }); + + // --------------------------------------------------------------------------- + // sortCharactersFirst (called by NextRoundCommand and SetScenarioCommand) + // --------------------------------------------------------------------------- + group('sortCharactersFirst via NextRoundCommand', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + test('all alive characters appear before active monsters', () { + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + final list = getIt<GameState>().currentList; + bool seenActiveMonster = false; + for (final item in list) { + if (item is Monster && item.isActive) seenActiveMonster = true; + if (item is Character && + item.characterState.health > 0 && + seenActiveMonster) { + fail('Alive character "${item.id}" appeared after an active monster'); + } + } + expect(list, isNotEmpty); + }); + + test('dead character is sorted after alive characters', () { + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + final bs = + getIt<GameState>().currentList.firstWhere( + (e) => e is Character && e.id == 'Banner Spear', + ) + as Character; + ChangeHealthCommand( + -bs.characterState.health, + bs.id, + bs.id, + gameState: getIt<GameState>(), + ).execute(); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + final list = getIt<GameState>().currentList; + final bbIdx = list.indexWhere( + (e) => e is Character && e.id == 'Blinkblade', + ); + final bsIdx = list.indexWhere( + (e) => e is Character && e.id == 'Banner Spear', + ); + expect( + bbIdx, + lessThan(bsIdx), + reason: 'Dead Banner Spear should appear after alive Blinkblade', + ); + }); + + test('inactive monster sorted after active monsters', () { + AddMonsterCommand( + 'Test Boss (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + // Test Boss has no standees → inactive + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + final list = getIt<GameState>().currentList; + final activeMonsterIdx = list.indexWhere( + (e) => e is Monster && e.isActive, + ); + final inactiveMonsterIdx = list.indexWhere( + (e) => e is Monster && !e.isActive, + ); + + if (activeMonsterIdx != -1 && inactiveMonsterIdx != -1) { + expect( + activeMonsterIdx, + lessThan(inactiveMonsterIdx), + reason: 'Active monster should come before inactive monster', + ); + } + }); + }); + + // --------------------------------------------------------------------------- + // drawAbilityCardFromInactiveDeck (called by AddStandeeCommand during playTurns) + // --------------------------------------------------------------------------- + group('drawAbilityCardFromInactiveDeck', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + }); + + test( + 'adding first standee during playTurns draws an ability card for the inactive deck', + () { + final zealot = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Zealot', + ) + as Monster; + final deck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == zealot.type.deck, + ); + + // Zealot has no standees so not drawn during DrawCommand + DrawCommand(gameState: getIt<GameState>()).execute(); + expect( + deck.discardPileIsEmpty, + isTrue, + reason: + 'Inactive Zealot should not have drawn a card during DrawCommand', + ); + + // Add first standee during playTurns → triggers drawAbilityCardFromInactiveDeck + AddStandeeCommand( + 1, + null, + zealot.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + expect( + deck.discardPileIsNotEmpty, + isTrue, + reason: + 'First standee during playTurns should trigger an ability card draw', + ); + }, + ); + + test( + 'adding additional standees to already-active monster does not draw extra cards', + () { + final zealot = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Zealot', + ) + as Monster; + final deck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == zealot.type.deck, + ); + + DrawCommand(gameState: getIt<GameState>()).execute(); + AddStandeeCommand( + 1, + null, + zealot.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + final sizeAfterFirst = deck.discardPileSize; + + // Second standee should NOT draw another card + AddStandeeCommand( + 2, + null, + zealot.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + expect( + deck.discardPileSize, + sizeAfterFirst, + reason: + 'Adding a second standee should not draw another ability card', + ); + }, + ); + }); + + // --------------------------------------------------------------------------- + // sortItemToPlace (called by AddStandeeCommand during playTurns) + // --------------------------------------------------------------------------- + group('sortItemToPlace via AddStandeeCommand during playTurns', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + }); + + test('monster placed before character when its drawn initiative is lower', () { + // Zealot's lowest card initiative is 27 — set character to 99 + SetInitCommand('Blinkblade', 99, gameState: getIt<GameState>()).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + + final zealot = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Zealot', + ) + as Monster; + AddStandeeCommand( + 1, + null, + zealot.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + final deck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == zealot.type.deck, + ); + final drawnInit = deck.discardPileTop.initiative; + + final list = getIt<GameState>().currentList; + final zealotIdx = list.indexWhere((e) => e.id == 'Zealot'); + final charIdx = list.indexWhere((e) => e is Character); + + // When monster's initiative < current item's initiative, sortItemToPlace + // places it AFTER the current item (not in strict initiative order). + if (drawnInit < 99) { + expect( + zealotIdx, + greaterThan(charIdx), + reason: + 'Zealot (init $drawnInit < 99) should be placed after current Blinkblade', + ); + } + }); + + test( + 'monster placed after character when its drawn initiative is higher', + () { + // Set character initiative very low so Chaos Demon comes after + SetInitCommand( + 'Blinkblade', + 1, + gameState: getIt<GameState>(), + ).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + + final chaosDemon = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Chaos Demon', + ) + as Monster; + AddStandeeCommand( + 1, + null, + chaosDemon.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + final deck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == chaosDemon.type.deck, + ); + final drawnInit = deck.discardPileTop.initiative; + + final list = getIt<GameState>().currentList; + final cdIdx = list.indexWhere((e) => e.id == 'Chaos Demon'); + final charIdx = list.indexWhere((e) => e is Character); + + if (drawnInit > 1) { + expect( + charIdx, + lessThan(cdIdx), + reason: + 'Blinkblade (init 1) should come before Chaos Demon (init $drawnInit)', + ); + } + }, + ); + }); + + // --------------------------------------------------------------------------- + // removeExpiringConditions (via TurnDoneCommand) + // --------------------------------------------------------------------------- + group('removeExpiringConditions via TurnDoneCommand', () { + late Character character; + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + test( + 'stun expires on character when turn advances (condition added before draw)', + () { + // Condition added in chooseInitiative → NOT tracked as "added this turn" + AddConditionCommand( + Condition.stun, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + expect(character.characterState.conditions, contains(Condition.stun)); + + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect( + character.characterState.conditions, + isNot(contains(Condition.stun)), + reason: + 'Stun added before round should expire when character turn advances', + ); + }, + ); + + test('poison does NOT expire when character turn advances', () { + AddConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect( + character.characterState.conditions, + contains(Condition.poison), + reason: 'Poison is not in the expiring list and should remain', + ); + }); + + test('muddle expires on character when turn advances', () { + AddConditionCommand( + Condition.muddle, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect( + character.characterState.conditions, + isNot(contains(Condition.muddle)), + reason: 'Muddle is expirable and should be removed on turn advance', + ); + }); + + test('immobilize expires on character when turn advances', () { + AddConditionCommand( + Condition.immobilize, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect( + character.characterState.conditions, + isNot(contains(Condition.immobilize)), + reason: 'Immobilize is expirable and should be removed on turn advance', + ); + }); + + test('stun on monster instance expires when monster turn advances', () { + AddConditionCommand( + Condition.stun, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + expect(monsterInstance.conditions, contains(Condition.stun)); + + DrawCommand(gameState: getIt<GameState>()).execute(); + // First call: notDone → current (no expiry yet) + TurnDoneCommand(monster.id, gameState: getIt<GameState>()).execute(); + // Second call: current → done (triggers removeExpiringConditions) + TurnDoneCommand(monster.id, gameState: getIt<GameState>()).execute(); + + expect( + monsterInstance.conditions, + isNot(contains(Condition.stun)), + reason: + 'Stun on monster instance should expire when monster turn advances', + ); + }); + + test( + 'wound on monster instance does NOT expire when monster turn advances', + () { + AddConditionCommand( + Condition.wound, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand(monster.id, gameState: getIt<GameState>()).execute(); + + expect( + monsterInstance.conditions, + contains(Condition.wound), + reason: 'Wound is not expirable and should remain', + ); + }, + ); + + test('stun added during active turn is NOT expired immediately', () { + DrawCommand(gameState: getIt<GameState>()).execute(); + // Character is current → condition is tracked as "added this turn" + AddConditionCommand( + Condition.stun, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect( + character.characterState.conditions, + contains(Condition.stun), + reason: + 'Stun added during own turn should NOT expire at end of that turn', + ); + }); + }); + + // --------------------------------------------------------------------------- + // setTurnDone edge cases + // --------------------------------------------------------------------------- + group('setTurnDone edge cases', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + }); + + test('dead character is skipped as next current figure', () { + final gs = getIt<GameState>(); + final bs = + gs.currentList.firstWhere( + (e) => e is Character && e.id == 'Banner Spear', + ) + as Character; + ChangeHealthCommand( + -bs.characterState.health, + bs.id, + bs.id, + gameState: getIt<GameState>(), + ).execute(); + + SetInitCommand('Blinkblade', 10, gameState: getIt<GameState>()).execute(); + SetInitCommand( + 'Banner Spear', + 20, + gameState: getIt<GameState>(), + ).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + + final bb = + gs.currentList.firstWhere( + (e) => e is Character && e.id == 'Blinkblade', + ) + as Character; + expect(bb.turnState, TurnsState.current); + + TurnDoneCommand(bb.id, gameState: getIt<GameState>()).execute(); + + expect( + bs.turnState, + isNot(TurnsState.current), + reason: 'Dead Banner Spear should never become current', + ); + }); + + test('inactive monster is skipped as next current figure', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + + SetInitCommand('Blinkblade', 50, gameState: getIt<GameState>()).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + + final bb = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + TurnDoneCommand(bb.id, gameState: getIt<GameState>()).execute(); + + final artillery = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + expect( + artillery.turnState, + isNot(TurnsState.current), + reason: 'Inactive monster should never become current', + ); + }); + + test('items before the clicked index are set to done', () { + SetInitCommand('Blinkblade', 10, gameState: getIt<GameState>()).execute(); + SetInitCommand( + 'Banner Spear', + 20, + gameState: getIt<GameState>(), + ).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + + final list = getIt<GameState>().currentList; + final bs = + list.firstWhere((e) => e is Character && e.id == 'Banner Spear') + as Character; + + // Click on Banner Spear (index 1) skips Blinkblade to done + TurnDoneCommand(bs.id, gameState: getIt<GameState>()).execute(); + + final bb = + list.firstWhere((e) => e is Character && e.id == 'Blinkblade') + as Character; + expect( + bb.turnState, + TurnsState.done, + reason: + 'Blinkblade at index 0 should be set to done when Banner Spear at index 1 is clicked', + ); + }); + + test('clicking a done item reverts it to current', () { + SetInitCommand('Blinkblade', 10, gameState: getIt<GameState>()).execute(); + SetInitCommand( + 'Banner Spear', + 20, + gameState: getIt<GameState>(), + ).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + + final list = getIt<GameState>().currentList; + final bb = + list.firstWhere((e) => e is Character && e.id == 'Blinkblade') + as Character; + + TurnDoneCommand( + bb.id, + gameState: getIt<GameState>(), + ).execute(); // current → done, next becomes current + expect(bb.turnState, TurnsState.done); + + TurnDoneCommand( + bb.id, + gameState: getIt<GameState>(), + ).execute(); // done → current (revert) + expect( + bb.turnState, + TurnsState.current, + reason: 'Clicking a done item should make it current again', + ); + }); + }); + + // --------------------------------------------------------------------------- + // shuffleDecksIfNeeded (called by NextRoundCommand) + // --------------------------------------------------------------------------- + group('shuffleDecksIfNeeded via NextRoundCommand', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + test( + 'ability deck with empty draw pile is reshuffled on NextRoundCommand', + () { + final zealot = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Zealot', + ) + as Monster; + final deck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == zealot.type.deck, + ); + + // Drain all cards from the draw pile + while (deck.drawPileIsNotEmpty) { + DrawAbilityCardCommand(zealot.id).execute(); + } + expect( + deck.drawPileIsEmpty, + isTrue, + reason: 'Precondition: draw pile should be empty', + ); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect( + deck.drawPileIsNotEmpty, + isTrue, + reason: 'Ability deck should be reshuffled when draw pile was empty', + ); + expect( + deck.discardPileIsEmpty, + isTrue, + reason: 'Discard pile should be empty after reshuffle', + ); + }, + ); + + test('ability deck with shuffle-card on top of discard is reshuffled', () { + final zealot = + getIt<GameState>().currentList.firstWhere( + (e) => e is Monster && e.id == 'Zealot', + ) + as Monster; + final deck = getIt<GameState>().currentAbilityDecks.firstWhere( + (d) => d.name == zealot.type.deck, + ); + + // Draw until a shuffle-flagged card lands on top of the discard pile. + // We drain the deck once; if no shuffle card appears, skip the assertion. + int attempts = 0; + while (deck.drawPileIsNotEmpty && attempts < 50) { + DrawAbilityCardCommand(zealot.id).execute(); + attempts++; + if (deck.discardPileIsNotEmpty && deck.discardPileTop.shuffle) break; + } + + if (deck.discardPileIsNotEmpty && deck.discardPileTop.shuffle) { + final discardSizeBefore = deck.discardPileSize; + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + expect( + deck.discardPileIsEmpty, + isTrue, + reason: + 'Discard pile should be empty after shuffle-triggered reshuffle', + ); + expect( + deck.drawPileSize, + greaterThanOrEqualTo(discardSizeBefore), + reason: 'Draw pile should contain all formerly discarded cards', + ); + } + // If we never got a shuffle card on top, the test is a no-op (inconclusive but not failing) + }); + }); + + // --------------------------------------------------------------------------- + // addPerk / removePerk – Hail perk 17 (adds special card to main modifier deck) + // --------------------------------------------------------------------------- + group('addPerk/removePerk – Hail perk 17 (Hail special card)', () { + late Character hail; + + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + // Reset the modifier deck between tests via SetScenarioCommand (section=false + // calls modifierDeck._initDeck() before we add our character) + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + // Hail's edition is "Mercenary Packs" (cross-edition character) + AddCharacterCommand('Hail', 'Mercenary Packs', 'H', 1).execute(); + hail = + getIt<GameState>().currentList.firstWhere( + (e) => e is Character && e.id == 'Hail', + ) + as Character; + }); + + test('adding Hail perk 17 adds special card to the main modifier deck', () { + final deckBefore = getIt<GameState>().modifierDeck.drawPileSize; + + AddPerkCommand(hail.id, 17).execute(); + + expect( + getIt<GameState>().modifierDeck.hasHail(), + isTrue, + reason: + 'Main modifier deck should contain the Hail special card after perk 17', + ); + expect( + getIt<GameState>().modifierDeck.drawPileSize, + greaterThan(deckBefore), + reason: + 'Main modifier deck size should increase after adding Hail perk 17', + ); + }); + + test( + 'removing Hail perk 17 removes special card from the main modifier deck', + () { + AddPerkCommand(hail.id, 17).execute(); + expect(getIt<GameState>().modifierDeck.hasHail(), isTrue); + + AddPerkCommand(hail.id, 17).execute(); // toggle off + + expect( + getIt<GameState>().modifierDeck.hasHail(), + isFalse, + reason: + 'Hail special card should be removed when perk 17 is toggled off', + ); + }, + ); + + test('main modifier deck card count is restored after add then remove', () { + final deckBefore = getIt<GameState>().modifierDeck.drawPileSize; + + AddPerkCommand(hail.id, 17).execute(); + AddPerkCommand(hail.id, 17).execute(); + + expect( + getIt<GameState>().modifierDeck.drawPileSize, + deckBefore, + reason: 'Deck count should be unchanged after toggling perk on and off', + ); + }); + }); + + // --------------------------------------------------------------------------- + // addPerk / removePerk – Pain Conduit perk 16 (max health +5) + // --------------------------------------------------------------------------- + group('addPerk/removePerk – Pain Conduit perk 16 (max health +5)', () { + late Character painConduit; + + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Pain Conduit', 'Frosthaven', 'PC', 1).execute(); + painConduit = + getIt<GameState>().currentList.firstWhere( + (e) => e is Character && e.id == 'Pain Conduit', + ) + as Character; + }); + + test('adding Pain Conduit perk 16 increases max health by 5', () { + final maxHealthBefore = painConduit.characterState.maxHealth; + + AddPerkCommand(painConduit.id, 16).execute(); + + expect( + painConduit.characterState.maxHealth, + maxHealthBefore + 5, + reason: 'Max health should increase by 5 for Pain Conduit perk 16', + ); + }); + + test('adding Pain Conduit perk 16 increases current health by 5', () { + final healthBefore = painConduit.characterState.health; + + AddPerkCommand(painConduit.id, 16).execute(); + + expect( + painConduit.characterState.health, + healthBefore + 5, + reason: 'Current health should also increase by 5', + ); + }); + + test('removing Pain Conduit perk 16 restores original max health', () { + final maxHealthBefore = painConduit.characterState.maxHealth; + + AddPerkCommand(painConduit.id, 16).execute(); + AddPerkCommand(painConduit.id, 16).execute(); // toggle off + + expect( + painConduit.characterState.maxHealth, + maxHealthBefore, + reason: + 'Max health should be restored to original after toggling perk off', + ); + }); + + test('Pain Conduit perk 16 bonus applies at a higher level', () { + SetCharacterLevelCommand(5, painConduit.id).execute(); + final maxHealthAtLevel5 = painConduit.characterState.maxHealth; + + AddPerkCommand(painConduit.id, 16).execute(); + + expect( + painConduit.characterState.maxHealth, + maxHealthAtLevel5 + 5, + reason: 'Perk 16 always adds exactly +5 regardless of level', + ); + }); + }); + + // --------------------------------------------------------------------------- + // setCharacterLevel – level capping and special character handling + // --------------------------------------------------------------------------- + group('setCharacterLevel special cases', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + }); + + test( + 'Pain Conduit with perk 16 active has correct health after level change', + () { + AddCharacterCommand('Pain Conduit', 'Frosthaven', 'PC', 1).execute(); + final pc = + getIt<GameState>().currentList.firstWhere( + (e) => e is Character && e.id == 'Pain Conduit', + ) + as Character; + + AddPerkCommand(pc.id, 16).execute(); + SetCharacterLevelCommand(3, pc.id).execute(); + + final baseHealth = + pc.characterClass.healthByLevel[2]; // level 3 = index 2 + expect( + pc.characterState.health, + baseHealth + 5, + reason: 'Pain Conduit with perk 16 should have base level health + 5', + ); + expect(pc.characterState.maxHealth, baseHealth + 5); + }, + ); + + test('character level is capped at max health table length', () { + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + final bb = + getIt<GameState>().currentList.firstWhere( + (e) => e is Character && e.id == 'Blinkblade', + ) + as Character; + + final maxLevel = bb.characterClass.healthByLevel.length; + SetCharacterLevelCommand(maxLevel + 5, bb.id).execute(); + + expect( + bb.characterState.level, + maxLevel, + reason: 'Level should be capped at the number of health table entries', + ); + }); + + test('character health and max health are updated on level change', () { + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + final bb = + getIt<GameState>().currentList.firstWhere( + (e) => e is Character && e.id == 'Blinkblade', + ) + as Character; + + SetCharacterLevelCommand(5, bb.id).execute(); + + final expectedHealth = + bb.characterClass.healthByLevel[4]; // level 5 = index 4 + expect(bb.characterState.health, expectedHealth); + expect(bb.characterState.maxHealth, expectedHealth); + }); + }); + + // --------------------------------------------------------------------------- + // clearTurnState (called by NextRoundCommand) + // --------------------------------------------------------------------------- + group('clearTurnState via NextRoundCommand', () { + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + test('all turn states are reset to notDone after NextRoundCommand', () { + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + for (final item in getIt<GameState>().currentList) { + expect( + item.turnState, + TurnsState.notDone, + reason: 'All items should be notDone after round end', + ); + } + }); + + test('conditions tracking is cleared at round end', () { + // Add stun during active turn (tracked as this turn) + DrawCommand(gameState: getIt<GameState>()).execute(); + AddConditionCommand( + Condition.stun, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + // Stun is tracked in conditionsAddedThisTurn + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + // conditionsAddedThisTurn → conditionsAddedPreviousTurn, and fresh turn starts + + // Round state should be chooseInitiative now + expect(getIt<GameState>().roundState, RoundState.chooseInitiative); + }); + }); + + // --------------------------------------------------------------------------- + // updateElements (called by NextRoundCommand) + // --------------------------------------------------------------------------- + group('updateElements via NextRoundCommand', () { + setUp(() { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + }); + + test('full element steps to half after NextRoundCommand', () { + ImbueElementCommand(Elements.fire, false).execute(); + expect(getIt<GameState>().elementState[Elements.fire], ElementState.full); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect(getIt<GameState>().elementState[Elements.fire], ElementState.half); + }); + + test('half element steps to inert after NextRoundCommand', () { + ImbueElementCommand(Elements.ice, true).execute(); // half + expect(getIt<GameState>().elementState[Elements.ice], ElementState.half); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect(getIt<GameState>().elementState[Elements.ice], ElementState.inert); + }); + + test('inert element stays inert after NextRoundCommand', () { + // earth is inert by default + expect( + getIt<GameState>().elementState[Elements.earth], + ElementState.inert, + ); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect( + getIt<GameState>().elementState[Elements.earth], + ElementState.inert, + ); + }); + + test('all six elements decay by one step each round', () { + ImbueElementCommand(Elements.fire, false).execute(); + ImbueElementCommand(Elements.ice, false).execute(); + ImbueElementCommand(Elements.air, false).execute(); + ImbueElementCommand(Elements.earth, false).execute(); + ImbueElementCommand(Elements.light, false).execute(); + ImbueElementCommand(Elements.dark, false).execute(); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + for (final element in Elements.values) { + expect( + getIt<GameState>().elementState[element], + ElementState.half, + reason: '${element.name} should step from full to half', + ); + } + }); + }); + + // --------------------------------------------------------------------------- + // resetElements (called by SetScenarioCommand) + // --------------------------------------------------------------------------- + group('resetElements via SetScenarioCommand', () { + test('all elements are reset to inert when loading a new scenario', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'BB', 1).execute(); + + ImbueElementCommand(Elements.fire, false).execute(); + ImbueElementCommand(Elements.light, true).execute(); + + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + + for (final element in Elements.values) { + expect( + getIt<GameState>().elementState[element], + ElementState.inert, + reason: '${element.name} should be inert after scenario reset', + ); + } + }); + }); +} diff --git a/server/test/command/next_round_command_test.dart b/server/test/command/next_round_command_test.dart new file mode 100644 index 0000000..dd7cc5a --- /dev/null +++ b/server/test/command/next_round_command_test.dart @@ -0,0 +1,174 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/commands/imbue_element_command.dart'; +import 'package:x_haven_server/core/commands/next_round_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'Blinky', 1).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('NextRoundCommand', () { + test('should increment the round counter', () { + final roundBefore = getIt<GameState>().round; + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect(getIt<GameState>().round, roundBefore + 1); + checkSaveState(); + }); + + test('should step down full elements to half after next round', () { + ImbueElementCommand(Elements.fire, false).execute(); + expect(getIt<GameState>().elementState[Elements.fire], ElementState.full); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect(getIt<GameState>().elementState[Elements.fire], ElementState.half); + }); + + test('should step down half elements to inert after next round', () { + ImbueElementCommand(Elements.ice, true).execute(); + expect(getIt<GameState>().elementState[Elements.ice], ElementState.half); + + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + + expect(getIt<GameState>().elementState[Elements.ice], ElementState.inert); + }); + + test('describe returns "Next Round"', () { + expect( + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).describe(), + 'Next Round', + ); + }); + + test('undo does not throw', () { + final gs = getIt<GameState>(); + gs.action( + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ), + ); + expect(() => gs.undo(), returnsNormally); + }); + + test('shuffles monster modifier deck when needsShuffle is true', () { + // Draw all cards to force needsShuffle + final gs = getIt<GameState>(); + final deck = gs.modifierDeck; + // Draw until needsShuffle is set (drawing a multiply/2x or curse usually does it) + int attempts = 0; + while (!deck.needsShuffle && attempts < 30) { + DrawModifierCardCommand('', gameState: getIt<GameState>()).execute(); + attempts++; + } + if (deck.needsShuffle) { + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + // After next round with needsShuffle, deck should be reshuffled + expect(deck.drawPileIsNotEmpty, isTrue); + } + }); + + test('character modifier deck needsShuffle is shuffled on next round', () { + final gs = getIt<GameState>(); + final character = + gs.currentList.firstWhere((e) => e is Character) as Character; + final deck = character.characterState.modifierDeck; + int attempts = 0; + while (!deck.needsShuffle && attempts < 30) { + DrawModifierCardCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); + attempts++; + } + if (deck.needsShuffle) { + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + expect(deck.drawPileIsNotEmpty, isTrue); + } + }); + + test('modifier deck ally needsShuffle is shuffled on next round', () { + final gs = getIt<GameState>(); + final deck = gs.modifierDeckAllies; + int attempts = 0; + while (!deck.needsShuffle && attempts < 30) { + DrawModifierCardCommand( + 'allies', + gameState: getIt<GameState>(), + ).execute(); + attempts++; + } + if (deck.needsShuffle) { + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + expect(deck.drawPileIsNotEmpty, isTrue); + } + }); + + test('roundState is reset to chooseInitiative after DrawCommand', () { + DrawCommand(gameState: getIt<GameState>()).execute(); + expect(getIt<GameState>().roundState, RoundState.playTurns); + NextRoundCommand( + gameState: getIt<GameState>(), + gameData: getIt<GameData>(), + settings: getIt<Settings>(), + ).execute(); + expect(getIt<GameState>().roundState, RoundState.chooseInitiative); + }); + }); +} diff --git a/server/test/command/next_turn_command_test.dart b/server/test/command/next_turn_command_test.dart new file mode 100644 index 0000000..89c0981 --- /dev/null +++ b/server/test/command/next_turn_command_test.dart @@ -0,0 +1,56 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/turn_done_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('TurnDoneCommand', () { + test('should set character turn to current when not current', () { + expect(character.turnState, isNot(TurnsState.current)); + + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect(character.turnState, TurnsState.current); + }); + + test('should mark character turn as done when current', () { + // First call sets to current + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + expect(character.turnState, TurnsState.current); + + // Second call sets to done + TurnDoneCommand(character.id, gameState: getIt<GameState>()).execute(); + + expect(character.turnState, TurnsState.done); + checkSaveState(); + }); + + test('describe includes character id', () { + final command = TurnDoneCommand( + character.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), "${character.id}'s turn done"); + }); + }); +} diff --git a/server/test/command/note_row_command_test.dart b/server/test/command/note_row_command_test.dart new file mode 100644 index 0000000..da14bc2 --- /dev/null +++ b/server/test/command/note_row_command_test.dart @@ -0,0 +1,142 @@ +// ignore_for_file: avoid-late-keyword, no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_note_row_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/remove_note_row_command.dart'; +import 'package:x_haven_server/core/commands/reorder_list_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_note_row_color_command.dart'; +import 'package:x_haven_server/core/commands/set_note_row_link_command.dart'; +import 'package:x_haven_server/core/commands/set_note_row_text_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + GameState gs() => getIt<GameState>(); + + setUp(() { + gs().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "Blinky", 1).execute(); + AddMonsterCommand("Zealot", 1, false, gameState: gs()).execute(); + }); + + int indexOfId(String id) => + gs().currentList.toList().indexWhere((e) => e.id == id); + + group('NoteRow commands', () { + test('unlinked note is added as its own row and survives save/load', () { + gs().action( + AddNoteRowCommand( + NoteRow.create('note1', text: 'remember'), + gameState: gs(), + ), + ); + + final match = gs().currentList.firstWhere((e) => e.id == 'note1'); + expect(match, isA<NoteRow>()); + expect((match as NoteRow).text, 'remember'); + checkSaveState(); + }); + + test('linked note is glued directly after its target', () { + // Link a note to the Zealot monster. + gs().action( + AddNoteRowCommand( + NoteRow.create('note1', text: 'focus first', linkedId: 'Zealot'), + gameState: gs(), + ), + ); + + final monsterIndex = indexOfId('Zealot'); + final noteIndex = indexOfId('note1'); + expect( + noteIndex, + monsterIndex + 1, + reason: 'linked note must sit immediately after its target', + ); + checkSaveState(); + }); + + test('note re-glues after the list is reordered', () { + gs().action( + AddNoteRowCommand( + NoteRow.create('note1', linkedId: 'Zealot'), + gameState: gs(), + ), + ); + + // Move the note to the very top; reflow should pull it back under Zealot. + final from = indexOfId('note1'); + gs().action(ReorderListCommand(0, from, gameState: gs())); + + final monsterIndex = indexOfId('Zealot'); + expect(indexOfId('note1'), monsterIndex + 1); + }); + + test( + 'linked note stays glued under its target through the draw (round start)', + () { + // Give the character an initiative and link a note to it. + SetInitCommand('Blinkblade', 25, gameState: gs()).execute(); + gs().action( + AddNoteRowCommand( + NoteRow.create('note1', linkedId: 'Blinkblade'), + gameState: gs(), + ), + ); + expect(indexOfId('note1'), indexOfId('Blinkblade') + 1); + + // Drawing for the round sorts the list by initiative (scattering notes, + // which have no initiative) and notifies via updateList.notify(). The + // reflow in the sort must still re-glue the note under its target. + gs().action(DrawCommand(gameState: gs())); + + expect( + indexOfId('note1'), + indexOfId('Blinkblade') + 1, + reason: 'note must follow its target across the initiative sort', + ); + }, + ); + + test('setText / setColor / link / unlink mutate the note', () { + gs().action(AddNoteRowCommand(NoteRow.create('note1'), gameState: gs())); + final note = + gs().currentList.firstWhere((e) => e.id == 'note1') as NoteRow; + + gs().action(SetNoteRowTextCommand('hello', 'note1', gameState: gs())); + expect(note.text, 'hello'); + + gs().action(SetNoteRowColorCommand(0xFFAA0000, 'note1', gameState: gs())); + expect(note.color, 0xFFAA0000); + + gs().action(SetNoteRowLinkCommand('note1', 'Zealot', 3, gameState: gs())); + expect(note.linkedId, 'Zealot'); + expect(note.standeeNr, 3); + + // Unlink clears the standee too. + gs().action(SetNoteRowLinkCommand('note1', '', 0, gameState: gs())); + expect(note.linkedId, ''); + expect(note.standeeNr, 0); + checkSaveState(); + }); + + test('remove deletes the note row', () { + gs().action(AddNoteRowCommand(NoteRow.create('note1'), gameState: gs())); + expect(indexOfId('note1') >= 0, true); + + gs().action(RemoveNoteRowCommand('note1', gameState: gs())); + expect(indexOfId('note1'), -1); + checkSaveState(); + }); + }); +} diff --git a/server/test/command/note_row_standee_death_test.dart b/server/test/command/note_row_standee_death_test.dart new file mode 100644 index 0000000..5586700 --- /dev/null +++ b/server/test/command/note_row_standee_death_test.dart @@ -0,0 +1,81 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_note_row_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + GameState gs() => getIt<GameState>(); + + test( + 'a note tied to a specific standee is deleted when that standee dies', + () { + gs().clearList(); + AddMonsterCommand("Zealot", 1, false, gameState: gs()).execute(); + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: gs(), + ).execute(); + final monster = + gs().currentList.firstWhere((e) => e is Monster) as Monster; + final instance = monster.monsterInstances.first; + final standeeNr = instance.standeeNr; + + // A note pinned to this standee, plus a whole-group note (standeeNr 0). + gs().action( + AddNoteRowCommand( + NoteRow.create( + 'standeeNote', + linkedId: monster.id, + standeeNr: standeeNr, + ), + gameState: gs(), + ), + ); + gs().action( + AddNoteRowCommand( + NoteRow.create('groupNote', linkedId: monster.id), + gameState: gs(), + ), + ); + expect(gs().currentList.any((e) => e.id == 'standeeNote'), true); + + // Defeat the standee (drop its health to 0). + gs().action( + ChangeHealthCommand( + -instance.health, + instance.getId(), + monster.id, + gameState: gs(), + ), + ); + + // The standee's note is gone; the whole-group note remains. + expect( + gs().currentList.any((e) => e.id == 'standeeNote'), + false, + reason: 'note tied to the defeated standee should be deleted', + ); + expect( + gs().currentList.any((e) => e.id == 'groupNote'), + true, + reason: 'whole-group note is not standee-specific and should remain', + ); + }, + ); +} diff --git a/server/test/command/remove_amd_card_command_test.dart b/server/test/command/remove_amd_card_command_test.dart new file mode 100644 index 0000000..a444cc0 --- /dev/null +++ b/server/test/command/remove_amd_card_command_test.dart @@ -0,0 +1,75 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/commands/remove_amd_card_command.dart'; +import 'package:x_haven_server/core/commands/return_removed_amd_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('RemoveAMDCardCommand', () { + test('should move card from discard to removed pile', () { + DrawModifierCardCommand('', gameState: getIt<GameState>()).execute(); + final deck = getIt<GameState>().modifierDeck; + final discardBefore = deck.discardPileSize; + final removedBefore = deck.removedPileSize; + + RemoveAMDCardCommand( + index: 0, + name: '', + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.discardPileSize, discardBefore - 1); + expect(deck.removedPileSize, removedBefore + 1); + checkSaveState(); + }); + + test('describe returns correct string', () { + final command = RemoveAMDCardCommand( + index: 0, + name: '', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Remove AMD card'); + }); + }); + + group('ReturnRemovedAMDCardCommand', () { + test('should move card from removed pile back to discard', () { + DrawModifierCardCommand('', gameState: getIt<GameState>()).execute(); + RemoveAMDCardCommand( + index: 0, + name: '', + gameState: getIt<GameState>(), + ).execute(); + final deck = getIt<GameState>().modifierDeck; + final discardBefore = deck.discardPileSize; + final removedBefore = deck.removedPileSize; + + ReturnRemovedAMDCardCommand( + index: 0, + name: '', + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.removedPileSize, removedBefore - 1); + expect(deck.discardPileSize, discardBefore + 1); + checkSaveState(); + }); + + test('describe returns correct string', () { + final command = ReturnRemovedAMDCardCommand( + index: 0, + name: '', + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Return removed AMD card'); + }); + }); +} diff --git a/server/test/command/remove_character_command_test.dart b/server/test/command/remove_character_command_test.dart new file mode 100644 index 0000000..f4793a4 --- /dev/null +++ b/server/test/command/remove_character_command_test.dart @@ -0,0 +1,30 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/remove_character_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void _tests() { + final oldState = gameState.toString(); + AddCharacterCommand("Hatchet", "Jaws of the Lion", "Arnold", 9).execute(); + RemoveCharacterCommand( + List.of([gameState.currentList.last as Character]), + gameState: getIt<GameState>(), + ).execute(); + test("removed ok", () { + expect(gameState.currentList.isEmpty, true); + expect(gameState.unlockedClasses.first, "Hatchet"); + + checkNoSideEffects(["unlockedClasses"], oldState); + checkSaveState(); + }); +} + +Future<void> main() async { + await setUpGame(); + _tests(); +} diff --git a/server/test/command/remove_condition_command_test.dart b/server/test/command/remove_condition_command_test.dart new file mode 100644 index 0000000..11bb79f --- /dev/null +++ b/server/test/command/remove_condition_command_test.dart @@ -0,0 +1,129 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_condition_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/remove_condition_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + group('RemoveConditionCommand', () { + test('should remove a condition from a character', () { + AddConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + expect(character.characterState.conditions, contains(Condition.poison)); + + RemoveConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect( + character.characterState.conditions, + isNot(contains(Condition.poison)), + ); + checkSaveState(); + }); + + test('should remove a condition from a monster instance', () { + AddConditionCommand( + Condition.wound, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + expect(monsterInstance.conditions, contains(Condition.wound)); + + RemoveConditionCommand( + Condition.wound, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(monsterInstance.conditions, isNot(contains(Condition.wound))); + }); + + test('should decrement chill counter when removing chill', () { + AddConditionCommand( + Condition.chill, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + AddConditionCommand( + Condition.chill, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + expect(character.characterState.chill, 2); + + RemoveConditionCommand( + Condition.chill, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(character.characterState.chill, 1); + }); + + test('describe should return correct string', () { + final command = RemoveConditionCommand( + Condition.stun, + character.id, + character.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Remove condition: stun'); + }); + }); +} diff --git a/server/test/command/remove_cs_party_card_command_test.dart b/server/test/command/remove_cs_party_card_command_test.dart new file mode 100644 index 0000000..3d8324f --- /dev/null +++ b/server/test/command/remove_cs_party_card_command_test.dart @@ -0,0 +1,54 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_cs_party_card_command.dart'; +import 'package:x_haven_server/core/commands/remove_cs_party_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('RemoveCSPartyCardCommand', () { + test('should remove party card from character modifier deck', () { + AddCSPartyCardCommand( + character.id, + 1, + gameState: getIt<GameState>(), + ).execute(); + final deck = character.characterState.modifierDeck; + expect(deck.hasCard('party/1'), isTrue); + + RemoveCSPartyCardCommand( + character.id, + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.hasCard('party/1'), isFalse); + checkSaveState(); + }); + + test('describe includes character id', () { + final command = RemoveCSPartyCardCommand( + character.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), '${character.id} remove party card'); + }); + }); +} diff --git a/server/test/command/remove_monster_command_test.dart b/server/test/command/remove_monster_command_test.dart new file mode 100644 index 0000000..1bcd3da --- /dev/null +++ b/server/test/command/remove_monster_command_test.dart @@ -0,0 +1,74 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/remove_monster_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + }); + + group('RemoveMonsterCommand', () { + test('should remove a single monster from the list', () { + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + expect(getIt<GameState>().currentList.whereType<Monster>().length, 1); + + RemoveMonsterCommand([monster], gameState: getIt<GameState>()).execute(); + + expect(getIt<GameState>().currentList.whereType<Monster>(), isEmpty); + checkSaveState(); + }); + + test( + 'describe returns "Remove all monsters" for multiple items in list', + () { + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + // Passing the same monster twice simulates a multi-monster list + final command = RemoveMonsterCommand([ + monster, + monster, + ], gameState: getIt<GameState>()); + expect(command.describe(), 'Remove all monsters'); + }, + ); + + test('describe includes monster type name for single monster', () { + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + final command = RemoveMonsterCommand([ + monster, + ], gameState: getIt<GameState>()); + expect(command.describe(), contains('Remove')); + }); + }); +} diff --git a/server/test/command/remove_special_loot_card_command_test.dart b/server/test/command/remove_special_loot_card_command_test.dart new file mode 100644 index 0000000..4c1ba1a --- /dev/null +++ b/server/test/command/remove_special_loot_card_command_test.dart @@ -0,0 +1,76 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_special_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/remove__special_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('RemoveSpecialLootCardCommand', () { + test('should remove special card 1418 from draw pile', () { + AddSpecialLootCardCommand(1418, gameState: getIt<GameState>()).execute(); + final lootDeck = getIt<GameState>().lootDeck; + expect(lootDeck.hasCard1418, isTrue); + + RemoveSpecialLootCardCommand( + 1418, + gameState: getIt<GameState>(), + ).execute(); + + expect(lootDeck.hasCard1418, isFalse); + checkSaveState(); + }); + + test('should remove special card 1419 from draw pile', () { + AddSpecialLootCardCommand(1419, gameState: getIt<GameState>()).execute(); + final lootDeck = getIt<GameState>().lootDeck; + expect(lootDeck.hasCard1419, isTrue); + + RemoveSpecialLootCardCommand( + 1419, + gameState: getIt<GameState>(), + ).execute(); + + expect(lootDeck.hasCard1419, isFalse); + checkSaveState(); + }); + + test('should do nothing for unknown card nr', () { + final lootDeck = getIt<GameState>().lootDeck; + final countBefore = lootDeck.drawPileSize; + + RemoveSpecialLootCardCommand( + 9999, + gameState: getIt<GameState>(), + ).execute(); + + expect(lootDeck.drawPileSize, countBefore); + }); + + test('describe includes the card number', () { + final command = RemoveSpecialLootCardCommand( + 1418, + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Remove Special loot card 1418'); + }); + }); +} diff --git a/server/test/command/reorder_list_command_test.dart b/server/test/command/reorder_list_command_test.dart new file mode 100644 index 0000000..f7b065f --- /dev/null +++ b/server/test/command/reorder_list_command_test.dart @@ -0,0 +1,124 @@ +// ignore_for_file: prefer-first, no-magic-number, avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/reorder_ability_list_command.dart'; +import 'package:x_haven_server/core/commands/reorder_list_command.dart'; +import 'package:x_haven_server/core/commands/reorder_modifier_list_command.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + group('ReorderListCommand', () { + test('should swap two items in the main list', () { + final list = getIt<GameState>().currentList; + final firstId = list[0].id; + final secondId = list[1].id; + + ReorderListCommand(0, 1, gameState: getIt<GameState>()).execute(); + + expect(getIt<GameState>().currentList[0].id, secondId); + expect(getIt<GameState>().currentList[1].id, firstId); + }); + + test('describe returns correct string', () { + expect( + ReorderListCommand(0, 1, gameState: getIt<GameState>()).describe(), + 'Reorder List', + ); + }); + + test('undo does not throw', () { + final gs = getIt<GameState>(); + gs.action(ReorderListCommand(0, 1, gameState: getIt<GameState>())); + expect(() => gs.undo(), returnsNormally); + }); + }); + + group('ReorderAbilityListCommand', () { + test('should reorder cards in a monster ability deck', () { + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + final deck = GameMethods.getDeck(monster.type.deck)!; + // Need at least 2 cards + if (deck.drawPileSize >= 2) { + final firstCardNr = deck.drawPileContents.toList()[0].nr; + final secondCardNr = deck.drawPileContents.toList()[1].nr; + + ReorderAbilityListCommand( + monster.type.deck, + 0, + 1, + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.drawPileContents.toList()[0].nr, secondCardNr); + expect(deck.drawPileContents.toList()[1].nr, firstCardNr); + } + }); + + test('describe returns correct string', () { + expect( + ReorderAbilityListCommand( + 'deck', + 0, + 1, + gameState: getIt<GameState>(), + ).describe(), + 'Reorder Ability Cards', + ); + }); + }); + + group('ReorderModifierListCommand', () { + test('should reorder cards in a modifier deck draw pile', () { + final deck = getIt<GameState>().modifierDeck; + if (deck.drawPileSize >= 2) { + final firstGfx = deck.drawPileContents.toList()[0].gfx; + final secondGfx = deck.drawPileContents.toList()[1].gfx; + + ReorderModifierListCommand( + 0, + 1, + '', + gameState: getIt<GameState>(), + ).execute(); + + expect(deck.drawPileContents.toList()[0].gfx, secondGfx); + expect(deck.drawPileContents.toList()[1].gfx, firstGfx); + } + }); + + test('describe returns correct string', () { + expect( + ReorderModifierListCommand( + 0, + 1, + '', + gameState: getIt<GameState>(), + ).describe(), + 'Reorder Modifier Cards', + ); + }); + }); +} diff --git a/server/test/command/return_modifier_card_command_test.dart b/server/test/command/return_modifier_card_command_test.dart new file mode 100644 index 0000000..cac044c --- /dev/null +++ b/server/test/command/return_modifier_card_command_test.dart @@ -0,0 +1,33 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/commands/return_modifier_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('ReturnModifierCardCommand', () { + test('should move top discard card back to draw pile', () { + DrawModifierCardCommand('', gameState: getIt<GameState>()).execute(); + final deck = getIt<GameState>().modifierDeck; + final drawBefore = deck.drawPileSize; + final discardBefore = deck.discardPileSize; + + ReturnModifierCardCommand('').execute(); + + expect(deck.drawPileSize, drawBefore + 1); + expect(deck.discardPileSize, discardBefore - 1); + checkSaveState(); + }); + + test('describe returns correct string', () { + final command = ReturnModifierCardCommand(''); + expect(command.describe(), 'Return modifier card to top'); + }); + }); +} diff --git a/server/test/command/set_ally_deck_in_og_gloom_command_test.dart b/server/test/command/set_ally_deck_in_og_gloom_command_test.dart new file mode 100644 index 0000000..8e1659d --- /dev/null +++ b/server/test/command/set_ally_deck_in_og_gloom_command_test.dart @@ -0,0 +1,66 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/set_ally_deck_in_og_gloom_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('SetAllyDeckInOgGloomCommand', () { + test('should set allyDeckInOGGloom to false', () { + SetAllyDeckInOgGloomCommand( + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().allyDeckInOGGloom, isFalse); + checkSaveState(); + }); + + test('should set allyDeckInOGGloom to true', () { + SetAllyDeckInOgGloomCommand( + false, + gameState: getIt<GameState>(), + ).execute(); + SetAllyDeckInOgGloomCommand( + true, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().allyDeckInOGGloom, isTrue); + checkSaveState(); + }); + + test('describe when false returns no-ally string', () { + final command = SetAllyDeckInOgGloomCommand( + false, + gameState: getIt<GameState>(), + ); + expect( + command.describe(), + 'No ally deck in 1st edition Gloomhaven campaigns', + ); + }); + + test('describe when true returns use-ally string', () { + final command = SetAllyDeckInOgGloomCommand( + true, + gameState: getIt<GameState>(), + ); + expect( + command.describe(), + 'Use Ally Deck in 1st edition Gloomhaven Campaigns', + ); + }); + + test('undo does not throw', () { + final gs = getIt<GameState>(); + gs.action( + SetAllyDeckInOgGloomCommand(true, gameState: getIt<GameState>()), + ); + expect(() => gs.undo(), returnsNormally); + }); + }); +} diff --git a/server/test/command/set_as_summon_command_test.dart b/server/test/command/set_as_summon_command_test.dart new file mode 100644 index 0000000..9bc4e64 --- /dev/null +++ b/server/test/command/set_as_summon_command_test.dart @@ -0,0 +1,90 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/set_as_summon_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Monster monster; + late MonsterInstance monsterInstance; + + setUp(() { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + monsterInstance = monster.monsterInstances.first; + }); + + group('SetAsSummonCommand', () { + test('should mark a monster instance as summoned', () { + SetAsSummonCommand( + true, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + expect(monsterInstance.roundSummoned, greaterThanOrEqualTo(1)); + }); + + test('should clear summon mark when summoned is false', () { + SetAsSummonCommand( + true, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + SetAsSummonCommand( + false, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ).execute(); + expect(monsterInstance.roundSummoned, -1); + }); + + test('describe when summoned is true mentions mark', () { + final command = SetAsSummonCommand( + true, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), contains('summon')); + }); + + test('describe when summoned is false mentions remove', () { + final command = SetAsSummonCommand( + false, + monsterInstance.getId(), + monster.id, + gameState: getIt<GameState>(), + ); + expect(command.describe(), contains('Remove')); + }); + }); +} diff --git a/server/test/command/set_auto_level_adjust_command_test.dart b/server/test/command/set_auto_level_adjust_command_test.dart new file mode 100644 index 0000000..d9cd253 --- /dev/null +++ b/server/test/command/set_auto_level_adjust_command_test.dart @@ -0,0 +1,51 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/set_auto_level_adjust_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('SetAutoLevelAdjustCommand', () { + test('should turn auto level adjust on', () { + final command = SetAutoLevelAdjustCommand( + true, + gameState: getIt<GameState>(), + ); + command.execute(); + expect(getIt<GameState>().autoScenarioLevel, isTrue); + checkSaveState(); + }); + + test('should turn auto level adjust off', () { + SetAutoLevelAdjustCommand(true, gameState: getIt<GameState>()).execute(); + final command = SetAutoLevelAdjustCommand( + false, + gameState: getIt<GameState>(), + ); + command.execute(); + expect(getIt<GameState>().autoScenarioLevel, isFalse); + checkSaveState(); + }); + + test('describe should say "on" when enabled', () { + final command = SetAutoLevelAdjustCommand( + true, + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Turn automatic level update on'); + }); + + test('describe should say "off" when disabled', () { + final command = SetAutoLevelAdjustCommand( + false, + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Turn automatic level update off'); + }); + }); +} diff --git a/server/test/command/set_campaign_command_test.dart b/server/test/command/set_campaign_command_test.dart new file mode 100644 index 0000000..1f214ed --- /dev/null +++ b/server/test/command/set_campaign_command_test.dart @@ -0,0 +1,33 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('SetCampaignCommand', () { + test('should set campaign to Frosthaven', () { + final command = SetCampaignCommand('Frosthaven'); + command.execute(); + expect(getIt<GameState>().currentCampaign, 'Frosthaven'); + checkSaveState(); + }); + + test('should set campaign to Jaws of the Lion', () { + final command = SetCampaignCommand('Jaws of the Lion'); + command.execute(); + expect(getIt<GameState>().currentCampaign, 'Jaws of the Lion'); + checkSaveState(); + }); + + test('describe should return correct string', () { + final command = SetCampaignCommand('Frosthaven'); + expect(command.describe(), 'Set Frosthaven campaign'); + }); + }); +} diff --git a/server/test/command/set_character_level_command_test.dart b/server/test/command/set_character_level_command_test.dart new file mode 100644 index 0000000..6faa86e --- /dev/null +++ b/server/test/command/set_character_level_command_test.dart @@ -0,0 +1,48 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/set_character_level_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('SetCharacterLevelCommand', () { + test('should set character level', () { + final command = SetCharacterLevelCommand(3, character.id); + command.execute(); + expect(character.characterState.level, 3); + checkSaveState(); + }); + + test('should update max health when level changes', () { + final healthAtLevel1 = character.characterState.maxHealth; + SetCharacterLevelCommand(5, character.id).execute(); + expect( + character.characterState.maxHealth, + greaterThanOrEqualTo(healthAtLevel1), + ); + }); + + test('describe should include character id', () { + final command = SetCharacterLevelCommand(3, 'Blinkblade'); + expect(command.describe(), "Set Blinkblade's Level"); + }); + }); +} diff --git a/server/test/command/set_difficulty_command_test.dart b/server/test/command/set_difficulty_command_test.dart new file mode 100644 index 0000000..d63571b --- /dev/null +++ b/server/test/command/set_difficulty_command_test.dart @@ -0,0 +1,35 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/set_difficulty_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('SetDifficultyCommand', () { + test('should set difficulty to given value', () { + final command = SetDifficultyCommand(2, gameState: getIt<GameState>()); + command.execute(); + expect(getIt<GameState>().difficulty, 2); + checkSaveState(); + }); + + test('should set difficulty to negative value', () { + final command = SetDifficultyCommand(-1, gameState: getIt<GameState>()); + command.execute(); + expect(getIt<GameState>().difficulty, -1); + checkSaveState(); + }); + + test('describe should include difficulty level', () { + final command = SetDifficultyCommand(3, gameState: getIt<GameState>()); + expect(command.describe(), 'Set difficulty level to 3'); + }); + }); +} diff --git a/server/test/command/set_figure_note_command_test.dart b/server/test/command/set_figure_note_command_test.dart new file mode 100644 index 0000000..835c8df --- /dev/null +++ b/server/test/command/set_figure_note_command_test.dart @@ -0,0 +1,78 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/set_figure_note_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + GameState gs() => getIt<GameState>(); + late Character character; + + setUp(() { + gs().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "Blinky", 1).execute(); + character = gs().currentList.firstWhere((e) => e is Character) as Character; + }); + + group('SetFigureNoteCommand', () { + test( + 'sets a character note (on the shared base) and survives save/load', + () { + expect(character.note, ''); + SetFigureNoteCommand( + 'poison next turn', + character.id, + gameState: gs(), + ).execute(); + + expect(character.note, 'poison next turn'); + // Round-trips the whole game through toJson/fromJson and asserts the + // serialized state is unchanged, proving the note persists. + checkSaveState(); + }, + ); + + test('sets a monster note and survives save/load', () { + AddMonsterCommand("Zealot", 1, false, gameState: gs()).execute(); + final monster = + gs().currentList.firstWhere((e) => e is Monster) as Monster; + expect(monster.note, ''); + + SetFigureNoteCommand( + 'focus first', + monster.id, + gameState: gs(), + ).execute(); + + expect(monster.note, 'focus first'); + checkSaveState(); + }); + + test('clears the note when set to empty', () { + SetFigureNoteCommand('temp', character.id, gameState: gs()).execute(); + expect(character.note, 'temp'); + + SetFigureNoteCommand('', character.id, gameState: gs()).execute(); + expect(character.note, ''); + checkSaveState(); + }); + + test('describe should return correct string', () { + final command = SetFigureNoteCommand( + 'note', + 'Blinkblade', + gameState: gs(), + ); + expect(command.describe(), 'Set note for Blinkblade'); + }); + }); +} diff --git a/server/test/command/set_init_command_test.dart b/server/test/command/set_init_command_test.dart new file mode 100644 index 0000000..1637566 --- /dev/null +++ b/server/test/command/set_init_command_test.dart @@ -0,0 +1,53 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('SetInitCommand', () { + test('should set initiative for a character', () { + final command = SetInitCommand( + character.id, + 15, + gameState: getIt<GameState>(), + ); + command.execute(); + expect(character.characterState.initiative, 15); + checkSaveState(); + }); + + test('should update initiative to a new value', () { + SetInitCommand(character.id, 10, gameState: getIt<GameState>()).execute(); + SetInitCommand(character.id, 25, gameState: getIt<GameState>()).execute(); + expect(character.characterState.initiative, 25); + }); + + test('describe should include character id', () { + final command = SetInitCommand( + 'Blinkblade', + 15, + gameState: getIt<GameState>(), + ); + expect(command.describe(), 'Set initiative of Blinkblade'); + }); + }); +} diff --git a/server/test/command/set_level_command_test.dart b/server/test/command/set_level_command_test.dart new file mode 100644 index 0000000..3a2c1a8 --- /dev/null +++ b/server/test/command/set_level_command_test.dart @@ -0,0 +1,55 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + }); + + group('SetLevelCommand', () { + test('should set global level when monsterId is null', () { + final command = SetLevelCommand(3, null); + command.execute(); + expect(getIt<GameState>().level, 3); + checkSaveState(); + }); + + test('should set a specific monster level when monsterId is provided', () { + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + + SetLevelCommand(4, monster.id).execute(); + + expect(monster.level, 4); + checkSaveState(); + }); + + test('describe without monsterId returns "Set Level"', () { + final command = SetLevelCommand(2, null); + expect(command.describe(), 'Set Level'); + }); + + test('describe with monsterId includes monster name', () { + final command = SetLevelCommand(2, 'Ancient Artillery (FH)'); + expect(command.describe(), "Set Ancient Artillery (FH)'s level"); + }); + }); +} diff --git a/server/test/command/set_loot_owner_command_test.dart b/server/test/command/set_loot_owner_command_test.dart new file mode 100644 index 0000000..00d95a9 --- /dev/null +++ b/server/test/command/set_loot_owner_command_test.dart @@ -0,0 +1,48 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/draw_loot_card_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_loot_owner_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'blinky', 1).execute(); + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + DrawLootCardCommand(gameState: getIt<GameState>()).execute(); + }); + + group('SetLootOwnerCommand', () { + test('should set owner on the loot card', () { + final lootDeck = getIt<GameState>().lootDeck; + final card = lootDeck.discardPileTop; + expect(card.owner, isEmpty); + + SetLootOwnerCommand('Blinkblade', card).execute(); + + expect(card.owner, 'Blinkblade'); + checkSaveState(); + }); + + test('describe returns correct string', () { + final lootDeck = getIt<GameState>().lootDeck; + final card = lootDeck.discardPileTop; + final command = SetLootOwnerCommand('Blinkblade', card); + expect(command.describe(), 'Set loot card owner'); + }); + }); +} diff --git a/server/test/command/set_scenario_command_test.dart b/server/test/command/set_scenario_command_test.dart new file mode 100644 index 0000000..cf6ebe2 --- /dev/null +++ b/server/test/command/set_scenario_command_test.dart @@ -0,0 +1,714 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_condition_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_xp_command.dart'; +import 'package:x_haven_server/core/commands/imbue_element_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/commands/show_ally_deck_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +// Test data availability: +// JotL monsters: Zealot, Chaos Demon, Blood Tumor, Rat Monstrosity, Black Sludge, Vermling Raider +// FH monsters: Ancient Artillery (FH) +// JotL scenarios usable: #5 (Zealot/Chaos Demon/Blood Tumor), #6 (Rat Monstrosity/Black Sludge) +// FH scenarios usable: #0 Howling in the Snow (Ancient Artillery FH), custom + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'apan', 1).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + }); + + // --------------------------------------------------------------------------- + // describe() + // --------------------------------------------------------------------------- + group('SetScenarioCommand describe()', () { + test('returns "Set Scenario" when section is false', () { + expect( + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).describe(), + 'Set Scenario', + ); + }); + + test('returns "Add Section" when section is true', () { + expect( + SetScenarioCommand( + '#door', + true, + gameState: getIt<GameState>(), + ).describe(), + 'Add Section', + ); + }); + }); + + // --------------------------------------------------------------------------- + // Basic scenario setup + // --------------------------------------------------------------------------- + group('SetScenarioCommand basic scenario setup', () { + test('sets scenario name on game state', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().scenario, '#5 A Deeper Understanding'); + }); + + test('loads correct number of monsters and ability decks', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final gs = getIt<GameState>(); + // #5 has Zealot, Chaos Demon, Blood Tumor + expect(gs.currentList.whereType<Monster>().length, 3); + expect(gs.currentAbilityDecks.length, 3); + checkSaveState(); + }); + + test('round is reset to 1', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().round, 1); + }); + + test('totalRounds is reset to 1', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().totalRounds, 1); + }); + + test('round state is set to chooseInitiative', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().roundState, RoundState.chooseInitiative); + }); + + test('showAllyDeck is false for scenario with no AllyDeck rule', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().showAllyDeck, isFalse); + }); + + test('no loot deck for JotL scenario', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().lootDeck.drawPileSize, 0); + }); + + test('loot deck populated for Frosthaven scenario with loot', () { + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().lootDeck.drawPileSize, greaterThan(0)); + checkSaveState(); + }); + + test('scenarioSectionsAdded is empty on fresh scenario', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().scenarioSectionsAdded, isEmpty); + }); + + test('scenarioSpecialRules is populated for scenario with rules', () { + // #6 has Allies and Objective rules + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().scenarioSpecialRules, isNotEmpty); + }); + + test('ability decks have cards in draw pile after scenario load', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + for (final deck in getIt<GameState>().currentAbilityDecks) { + expect(deck.drawPileIsNotEmpty, isTrue); + } + }); + + test('modifier deck discard pile is empty after scenario load', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().modifierDeck.discardPileIsEmpty, isTrue); + }); + + test('modifier deck draw pile is not empty after scenario load', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().modifierDeck.drawPileIsNotEmpty, isTrue); + }); + }); + + // --------------------------------------------------------------------------- + // Character state reset + // --------------------------------------------------------------------------- + group('SetScenarioCommand character state reset', () { + test('character initiative is reset to 0', () { + final character = getIt<GameState>().currentList.first as Character; + SetInitCommand(character.id, 42, gameState: getIt<GameState>()).execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final after = getIt<GameState>().currentList.first as Character; + expect(after.characterState.initiative, 0); + }); + + test('character xp is reset to 0', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final character = getIt<GameState>().currentList.first as Character; + ChangeXPCommand( + 10, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + // Load a different scenario to trigger reset + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final after = + getIt<GameState>().currentList.firstWhere( + (e) => + e is Character && + !GameMethods.isObjectiveOrEscort(e.characterClass), + ) + as Character; + expect(after.characterState.xp, 0); + }); + + test('character conditions are cleared', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final character = getIt<GameState>().currentList.first as Character; + AddConditionCommand( + Condition.poison, + character.id, + character.id, + gameState: getIt<GameState>(), + ).execute(); + expect(character.characterState.conditions, contains(Condition.poison)); + + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + + final after = + getIt<GameState>().currentList.firstWhere( + (e) => + e is Character && + !GameMethods.isObjectiveOrEscort(e.characterClass), + ) + as Character; + expect(after.characterState.conditions, isEmpty); + }); + + test('character health is restored to max on reset', () { + final character = getIt<GameState>().currentList.first as Character; + final maxHp = character.characterState.maxHealth; + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final after = getIt<GameState>().currentList.first as Character; + expect(after.characterState.health, maxHp); + }); + + test('normal characters are preserved across scenario changes', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final characters = getIt<GameState>().currentList.whereType<Character>(); + expect( + characters.any( + (c) => !GameMethods.isObjectiveOrEscort(c.characterClass), + ), + isTrue, + ); + }); + + test('objectives from previous scenario are removed on new scenario', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + expect( + getIt<GameState>().currentList.any( + (item) => + item is Character && + GameMethods.isObjectiveOrEscort(item.characterClass), + ), + isTrue, + ); + + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + + expect( + getIt<GameState>().currentList.any( + (item) => + item is Character && + GameMethods.isObjectiveOrEscort(item.characterClass), + ), + isFalse, + ); + }); + + test('previous scenario monsters are replaced on new scenario', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + // #5 has Zealot + expect( + getIt<GameState>().currentList.whereType<Monster>().any( + (m) => m.id == 'Zealot', + ), + isTrue, + ); + + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + + // #6 has Rat Monstrosity and Black Sludge, not Zealot + expect( + getIt<GameState>().currentList.whereType<Monster>().any( + (m) => m.id == 'Zealot', + ), + isFalse, + reason: 'Zealot from #5 should not be present in #6', + ); + expect( + getIt<GameState>().currentList.whereType<Monster>().any( + (m) => m.id == 'Rat Monstrosity', + ), + isTrue, + ); + }); + + test('previous ability decks are replaced on new scenario', () { + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final decksAfterFirst = getIt<GameState>().currentAbilityDecks + .map((d) => d.name) + .toSet(); + + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final decksAfterSecond = getIt<GameState>().currentAbilityDecks + .map((d) => d.name) + .toSet(); + + expect(decksAfterSecond, isNot(equals(decksAfterFirst))); + }); + }); + + // --------------------------------------------------------------------------- + // Element reset + // --------------------------------------------------------------------------- + group('SetScenarioCommand element reset', () { + test('all elements are reset to inert on new scenario', () { + ImbueElementCommand(Elements.fire, false).execute(); + ImbueElementCommand(Elements.ice, false).execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final elementState = getIt<GameState>().elementState; + for (final element in Elements.values) { + expect( + elementState[element], + ElementState.inert, + reason: '${element.name} should be inert', + ); + } + }); + }); + + // --------------------------------------------------------------------------- + // Ally / Ally deck rules + // --------------------------------------------------------------------------- + group('SetScenarioCommand ally rules', () { + // #6 Corrupted Research (JotL): "Allies": ["Rat Monstrosity"] + test('monsters listed in Allies rule are marked isAlly', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final ratMonstrosity = getIt<GameState>().currentList + .whereType<Monster>() + .firstWhere((m) => m.id == 'Rat Monstrosity'); + expect(ratMonstrosity.isAlly, isTrue); + }); + + test('monsters not in Allies rule are not marked isAlly', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final blackSludge = getIt<GameState>().currentList + .whereType<Monster>() + .firstWhere((m) => m.id == 'Black Sludge'); + expect(blackSludge.isAlly, isFalse); + }); + + test( + 'shouldShowAlliesDeck returns true when allied monsters are present', + () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(GameMethods.shouldShowAlliesDeck(), isTrue); + }, + ); + + test('showAllyDeck flag stays false when allies come from "Allies" rule ' + 'rather than "AllyDeck" rule', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + // The Allies rule marks monsters as isAlly but does NOT set showAllyDeck + expect(getIt<GameState>().showAllyDeck, isFalse); + }); + + test( + 'showAllyDeck is reset to false when loading a scenario without AllyDeck rule', + () { + // Start from a state where showAllyDeck is true (set manually via ShowAllyDeckCommand) + ShowAllyDeckCommand().execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().showAllyDeck, isFalse); + }, + ); + }); + + // --------------------------------------------------------------------------- + // Objective special rule + // --------------------------------------------------------------------------- + group('SetScenarioCommand Objective special rule', () { + test('all 7 objectives from #6 Corrupted Research are added to list', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final objectives = getIt<GameState>().currentList.where( + (item) => + item is Character && + GameMethods.isObjectiveOrEscort(item.characterClass), + ); + expect(objectives.length, 7); + checkSaveState(); + }); + + test('objective display names match scenario data (Growth 1–7)', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + final names = getIt<GameState>().currentList + .whereType<Character>() + .where((c) => GameMethods.isObjectiveOrEscort(c.characterClass)) + .map((c) => c.characterState.display) + .toSet(); + for (int i = 1; i <= 7; i++) { + expect(names, contains('Growth $i')); + } + }); + + test('objectives have positive health', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + for (final obj + in getIt<GameState>().currentList.whereType<Character>().where( + (c) => GameMethods.isObjectiveOrEscort(c.characterClass), + )) { + expect(obj.characterState.health, greaterThan(0)); + } + }); + + test('objectives are IsObjectiveOrEscort characters', () { + SetScenarioCommand( + '#6 Corrupted Research', + false, + gameState: getIt<GameState>(), + ).execute(); + for (final obj + in getIt<GameState>().currentList.whereType<Character>().where( + (c) => GameMethods.isObjectiveOrEscort(c.characterClass), + )) { + expect(GameMethods.isObjectiveOrEscort(obj.characterClass), isTrue); + } + }); + }); + + // --------------------------------------------------------------------------- + // undo() coverage + // --------------------------------------------------------------------------- + group('SetScenarioCommand undo', () { + test('undo does not throw', () { + final gs = getIt<GameState>(); + gs.action( + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ), + ); + expect(() => gs.undo(), returnsNormally); + }); + }); + + // --------------------------------------------------------------------------- + // Custom scenarios + // --------------------------------------------------------------------------- + group('SetScenarioCommand custom scenarios', () { + test('Frosthaven custom scenario creates a loot deck', () { + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().lootDeck.drawPileSize, greaterThan(0)); + checkSaveState(); + }); + + test('non-Frosthaven custom scenario has no loot deck', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().lootDeck.drawPileSize, 0); + }); + + test('custom scenario has no monsters', () { + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().currentList.whereType<Monster>(), isEmpty); + }); + + test('custom scenario has no ability decks', () { + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + 'custom', + false, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().currentAbilityDecks, isEmpty); + }); + }); + + // --------------------------------------------------------------------------- + // Sections + // Test data: FH '#0 Howling in the Snow' has one test section: '#0.1 The Frozen Depths' + // --------------------------------------------------------------------------- + group('SetScenarioCommand sections', () { + const String baseScenario = '#0 Howling in the Snow'; + const String sectionName = '#0.1 The Frozen Depths'; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', 'apan', 1).execute(); + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + baseScenario, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + test('section name is tracked in scenarioSectionsAdded', () { + SetScenarioCommand( + sectionName, + true, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().scenarioSectionsAdded, contains(sectionName)); + checkSaveState(); + }); + + test('adding the same section twice records it twice', () { + SetScenarioCommand( + sectionName, + true, + gameState: getIt<GameState>(), + ).execute(); + SetScenarioCommand( + sectionName, + true, + gameState: getIt<GameState>(), + ).execute(); + expect( + getIt<GameState>().scenarioSectionsAdded + .where((s) => s == sectionName) + .length, + 2, + ); + }); + + test( + 'scenarioSectionsAdded is cleared when a new base scenario is loaded', + () { + SetScenarioCommand( + sectionName, + true, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().scenarioSectionsAdded, isNotEmpty); + + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + + expect(getIt<GameState>().scenarioSectionsAdded, isEmpty); + }, + ); + + test('adding a section does not remove previously-added monsters', () { + // Manually add a known monster after loading the base scenario + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monstersBefore = getIt<GameState>().currentList + .whereType<Monster>() + .length; + + SetScenarioCommand( + sectionName, + true, + gameState: getIt<GameState>(), + ).execute(); + + expect( + getIt<GameState>().currentList.whereType<Monster>().length, + greaterThanOrEqualTo(monstersBefore), + ); + }); + + test('section does not reset round or scenario name', () { + final roundBefore = getIt<GameState>().round; + final scenarioBefore = getIt<GameState>().scenario; + SetScenarioCommand( + sectionName, + true, + gameState: getIt<GameState>(), + ).execute(); + expect(getIt<GameState>().round, roundBefore); + expect(getIt<GameState>().scenario, scenarioBefore); + }); + }); +} diff --git a/server/test/command/set_solo_command_test.dart b/server/test/command/set_solo_command_test.dart new file mode 100644 index 0000000..3ac9c21 --- /dev/null +++ b/server/test/command/set_solo_command_test.dart @@ -0,0 +1,39 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/set_solo_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('SetSoloCommand', () { + test('should set solo to true', () { + final command = SetSoloCommand(true); + command.execute(); + expect(getIt<GameState>().solo, isTrue); + checkSaveState(); + }); + + test('should set solo to false', () { + SetSoloCommand(true).execute(); + final command = SetSoloCommand(false); + command.execute(); + expect(getIt<GameState>().solo, isFalse); + checkSaveState(); + }); + + test('describe should return solo recommendation string when true', () { + final command = SetSoloCommand(true); + expect(command.describe(), 'Set solo level recommendation on'); + }); + + test('describe should return regular recommendation string when false', () { + final command = SetSoloCommand(false); + expect(command.describe(), 'Set solo level recommendation off'); + }); + }); +} diff --git a/server/test/command/show_ally_deck_command_test.dart b/server/test/command/show_ally_deck_command_test.dart new file mode 100644 index 0000000..d1652ea --- /dev/null +++ b/server/test/command/show_ally_deck_command_test.dart @@ -0,0 +1,45 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/hide_ally_deck_command.dart'; +import 'package:x_haven_server/core/commands/show_ally_deck_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('ShowAllyDeckCommand', () { + test('should set showAllyDeck to true', () { + HideAllyDeckCommand().execute(); + expect(getIt<GameState>().showAllyDeck, isFalse); + + ShowAllyDeckCommand().execute(); + + expect(getIt<GameState>().showAllyDeck, isTrue); + checkSaveState(); + }); + + test('describe should return correct string', () { + expect(ShowAllyDeckCommand().describe(), 'Show Ally Deck'); + }); + }); + + group('HideAllyDeckCommand', () { + test('should set showAllyDeck to false', () { + ShowAllyDeckCommand().execute(); + expect(getIt<GameState>().showAllyDeck, isTrue); + + HideAllyDeckCommand().execute(); + + expect(getIt<GameState>().showAllyDeck, isFalse); + checkSaveState(); + }); + + test('describe should return correct string', () { + expect(HideAllyDeckCommand().describe(), 'Hide Ally Deck'); + }); + }); +} diff --git a/server/test/command/shuffle_ability_card_command_test.dart b/server/test/command/shuffle_ability_card_command_test.dart new file mode 100644 index 0000000..10eee0d --- /dev/null +++ b/server/test/command/shuffle_ability_card_command_test.dart @@ -0,0 +1,93 @@ +// ignore_for_file: avoid-late-keyword, avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/draw_ability_card_command.dart'; +import 'package:x_haven_server/core/commands/shuffle_ability_card_command.dart'; +import 'package:x_haven_server/core/commands/shuffle_amd_card_command.dart'; +import 'package:x_haven_server/core/commands/shuffle_drawn_ability_card_command.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Monster monster; + + setUp(() { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + }); + + group('ShuffleAbilityCardCommand', () { + test('should shuffle ability deck (discard into draw pile)', () { + // Draw some cards into discard + DrawAbilityCardCommand(monster.id).execute(); + DrawAbilityCardCommand(monster.id).execute(); + final deck = GameMethods.getDeck(monster.type.deck)!; + expect(deck.discardPileIsNotEmpty, isTrue); + + ShuffleAbilityCardCommand(monster.id).execute(); + + expect(deck.discardPileContents, isEmpty); + checkSaveState(); + }); + + test('describe returns correct string', () { + expect( + ShuffleAbilityCardCommand(monster.id).describe(), + 'Extra ability deck shuffle', + ); + }); + }); + + group('ShuffleDrawnAbilityCardCommand', () { + test('should shuffle only undrawn part of ability deck', () { + final deck = GameMethods.getDeck(monster.type.deck)!; + final totalBefore = deck.drawPileSize + deck.discardPileSize; + + ShuffleDrawnAbilityCardCommand(monster.type.deck).execute(); + + final totalAfter = deck.drawPileSize + deck.discardPileSize; + expect(totalAfter, totalBefore); + }); + + test('describe returns correct string', () { + expect( + ShuffleDrawnAbilityCardCommand(monster.type.deck).describe(), + 'Drawn ability deck shuffle', + ); + }); + }); + + group('ShuffleAMDCardCommand', () { + test('describe returns correct string', () { + expect( + ShuffleAMDCardCommand('', gameState: getIt<GameState>()).describe(), + 'Extra AMD deck shuffle', + ); + }); + + test('should shuffle modifier deck draw pile', () { + final deck = getIt<GameState>().modifierDeck; + final sizeBefore = deck.drawPileSize; + + ShuffleAMDCardCommand('', gameState: getIt<GameState>()).execute(); + + expect(deck.drawPileSize, sizeBefore); + }); + }); +} diff --git a/server/test/command/test_helpers.dart b/server/test/command/test_helpers.dart new file mode 100644 index 0000000..67e6f16 --- /dev/null +++ b/server/test/command/test_helpers.dart @@ -0,0 +1,56 @@ +// ignore_for_file: no-magic-number, avoid-late-keyword, avoid-top-level-members-in-tests + +import 'dart:convert'; + +import 'package:x_haven_server/core/game_data.dart'; +import 'package:x_haven_server/core/save_store.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:json_diff/json_diff.dart'; + +late final GameState gameState; + +/// Bootstraps the headless engine with the test data set. +/// +/// Mirror of the reference app's `setUpGame()`: registers the core +/// singletons with an in-memory save store, initializes the game state, loads +/// the test data from `assets/testData/`, and restores the (empty) save. +Future<void> setUpGame() async { + setupCore(saveStore: InMemorySaveStore()); + gameState = getIt<GameState>(); + //initialize game + gameState.init(); + await getIt<GameData>().loadData('assets/testData/'); + gameState.load(); +} + +void checkSaveState() { + String state = gameState.toString(); + int nrStates = gameState.gameSaveStates.length; + gameState.save(); + gameState.load(); + String newState = gameState.toString(); + assert( + gameState.gameSaveStates.length == nrStates + 2, + ); //for some reason a null state is added on load. + assert(newState == state); +} + +void checkNoSideEffects(List<String> changedFields, String oldState) { + final differ = JsonDiffer.fromJson( + json.decode(oldState), + json.decode(gameState.toString()), + ); + DiffNode diff = differ.diff(); + + diff.forEach((s, dn) { + print("for each"); + print(s); + assert(changedFields.contains(s)); + print(dn.added); + print(dn.moved); + print(dn.removed); + print(dn.changed); + print(dn.node); + }); +} diff --git a/server/test/command/track_standees_command_test.dart b/server/test/command/track_standees_command_test.dart new file mode 100644 index 0000000..cb4e0b4 --- /dev/null +++ b/server/test/command/track_standees_command_test.dart @@ -0,0 +1,97 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/track_standees_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + getIt<Settings>().noStandees = false; + }); + + group('TrackStandeesCommand', () { + test('should set noStandees to true when track is false', () { + TrackStandeesCommand( + false, + gameState: getIt<GameState>(), + settings: getIt<Settings>(), + ).execute(); + expect(getIt<Settings>().noStandees, isTrue); + }); + + test('should set noStandees to false when track is true', () { + TrackStandeesCommand( + false, + gameState: getIt<GameState>(), + settings: getIt<Settings>(), + ).execute(); + TrackStandeesCommand( + true, + gameState: getIt<GameState>(), + settings: getIt<Settings>(), + ).execute(); + expect(getIt<Settings>().noStandees, isFalse); + }); + + test('should clear monster instances when switching to no-track mode', () { + AddMonsterCommand( + 'Ancient Artillery (FH)', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = + getIt<GameState>().currentList.firstWhere((e) => e is Monster) + as Monster; + expect(monster.monsterInstances, isNotEmpty); + + TrackStandeesCommand( + false, + gameState: getIt<GameState>(), + settings: getIt<Settings>(), + ).execute(); + + expect(monster.monsterInstances, isEmpty); + }); + + test('describe returns correct string when track is false', () { + expect( + TrackStandeesCommand( + false, + gameState: getIt<GameState>(), + settings: getIt<Settings>(), + ).describe(), + "Don't track standees", + ); + }); + + test('describe returns correct string when track is true', () { + expect( + TrackStandeesCommand( + true, + gameState: getIt<GameState>(), + settings: getIt<Settings>(), + ).describe(), + 'Track standees', + ); + }); + }); +} diff --git a/server/test/command/use_element_command_test.dart b/server/test/command/use_element_command_test.dart new file mode 100644 index 0000000..f4434e9 --- /dev/null +++ b/server/test/command/use_element_command_test.dart @@ -0,0 +1,40 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/imbue_element_command.dart'; +import 'package:x_haven_server/core/commands/use_element_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + group('UseElementCommand', () { + test('should set element state to inert', () { + ImbueElementCommand(Elements.fire, false).execute(); + expect(getIt<GameState>().elementState[Elements.fire], ElementState.full); + + UseElementCommand(Elements.fire).execute(); + + expect( + getIt<GameState>().elementState[Elements.fire], + ElementState.inert, + ); + checkSaveState(); + }); + + test('should work on any element', () { + ImbueElementCommand(Elements.ice, false).execute(); + UseElementCommand(Elements.ice).execute(); + expect(getIt<GameState>().elementState[Elements.ice], ElementState.inert); + }); + + test('describe should include element name', () { + final command = UseElementCommand(Elements.earth); + expect(command.describe(), 'Use Element earth'); + }); + }); +} diff --git a/server/test/command/use_fh_perks_command_test.dart b/server/test/command/use_fh_perks_command_test.dart new file mode 100644 index 0000000..3b19ce8 --- /dev/null +++ b/server/test/command/use_fh_perks_command_test.dart @@ -0,0 +1,50 @@ +// ignore_for_file: avoid-late-keyword + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/use_fh_perks_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import 'test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + late Character character; + + setUp(() { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', 'BS', 1).execute(); + character = + getIt<GameState>().currentList.firstWhere((e) => e is Character) + as Character; + }); + + group('UseFHPerksCommand', () { + test('should toggle useFHPerks from false to true', () { + expect(character.characterState.useFHPerks, isFalse); + + UseFHPerksCommand(character.id).execute(); + + expect(character.characterState.useFHPerks, isTrue); + checkSaveState(); + }); + + test('should toggle useFHPerks from true to false', () { + UseFHPerksCommand(character.id).execute(); + expect(character.characterState.useFHPerks, isTrue); + + UseFHPerksCommand(character.id).execute(); + + expect(character.characterState.useFHPerks, isFalse); + }); + + test('describe should include character id', () { + final command = UseFHPerksCommand(character.id); + expect(command.describe(), contains(character.id)); + }); + }); +} diff --git a/server/test/integration/headless_round_test.dart b/server/test/integration/headless_round_test.dart new file mode 100644 index 0000000..4b1f034 --- /dev/null +++ b/server/test/integration/headless_round_test.dart @@ -0,0 +1,183 @@ +// ignore_for_file: no-magic-number + +/// Headless full-round integration test (Phase 1 / Milestone M1). +/// +/// Drives the ported engine through a complete game round using only +/// command invocations — no UI, no network: +/// scenario setup → characters → initiative → draw → turns → next round → +/// round 2 (and a first turn of round 2 advanced to round 3). +library; + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/commands/turn_done_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_actions.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + test('full round: setup, initiative, draw, turns, next round, round 2', () { + final gs = getIt<GameState>(); + final settings = getIt<Settings>(); + gs.clearList(); + settings.noInit = false; // force the initiative requirement + + // --- Scenario setup ---------------------------------------------------- + // 'custom' is the no-data scenario used throughout the reference test + // suite (named scenarios in the test data reference monsters that are + // not in the test monster table). + gs.action(SetCampaignCommand('Frosthaven')); + gs.action(SetScenarioCommand('custom', false, gameState: gs)); + expect(gs.currentCampaign, 'Frosthaven'); + expect(gs.scenario, 'custom'); + expect(gs.roundState, RoundState.chooseInitiative); + + // --- Figures ----------------------------------------------------------- + gs.action(AddCharacterCommand('Blinkblade', 'Frosthaven', 'Blinky', 1)); + gs.action(AddCharacterCommand('Banner Spear', 'Frosthaven', 'Spear', 1)); + gs.action( + AddMonsterCommand('Ancient Artillery (FH)', 2, false, gameState: gs), + ); + expect(gs.currentList.whereType<Character>().length, 2); + expect(gs.currentList.whereType<Monster>().length, 1); + // A monster only joins combat (takes turns) once a standee is placed on + // it — the reference app's auto-add dialog is UI, so we do it explicitly. + gs.action( + AddStandeeCommand( + 1, + null, + 'Ancient Artillery (FH)', + MonsterType.normal, + false, + gameState: gs, + ), + ); + final addedMonster = + gs.currentList.firstWhere((e) => e is Monster) as Monster; + expect(addedMonster.isActive, isTrue); + + // --- Initiative (secret until every player has entered) ---------------- + gs.action(SetInitCommand('Blinkblade', 4, gameState: gs)); + expect( + GameMethods.canDraw(), + isFalse, + reason: 'Banner Spear has not entered initiative yet', + ); + final blocked = runDrawOrNextRoundAction(gs); + expect(blocked.isBlocked, isTrue, reason: 'draw must wait for all inits'); + + gs.action(SetInitCommand('Banner Spear', 2, gameState: gs)); + expect(GameMethods.canDraw(), isTrue); + + // --- Draw --------------------------------------------------------------- + final indexBeforeDraw = gs.commandIndex; + expect(runDrawOrNextRoundAction(gs), same(DrawOrNextRoundResult.success)); + expect(gs.commandIndex, indexBeforeDraw + 1); + expect(gs.roundState, RoundState.playTurns); + + // Lower initiative acts first: Spear (2) before Blinky (4). + expect(gs.currentList.whereType<Character>().map((c) => c.id), [ + 'Banner Spear', + 'Blinkblade', + ]); + expect( + gs.currentList.any((e) => e.turnState == TurnsState.current), + isTrue, + reason: 'the first figure starts its turn', + ); + + // --- Turns: each active figure takes exactly one turn ------------------ + String? lastTurnedId; + var turns = 0; + while (gs.currentList.any((e) => e.turnState == TurnsState.current) && + turns < 10) { + final currentId = gs.currentList + .firstWhere((e) => e.turnState == TurnsState.current) + .id; + final indexBeforeTurn = gs.commandIndex; + gs.action(TurnDoneCommand(currentId, gameState: gs)); + expect( + gs.commandIndex, + indexBeforeTurn + 1, + reason: 'command index advances per action', + ); + lastTurnedId = currentId; + turns++; + } + expect( + turns, + gs.currentList.length, + reason: 'every figure (2 characters + 1 monster) took a turn', + ); + expect( + gs.currentList.every((e) => e.turnState == TurnsState.done), + isTrue, + reason: 'no figure left with a turn pending', + ); + + // --- Undo/redo of the last turn ----------------------------------------- + gs.undo(); + expect( + gs.currentList.firstWhere((e) => e.id == lastTurnedId).turnState, + TurnsState.current, + reason: 'undo restores the finished turn', + ); + gs.redo(); + expect( + gs.currentList.firstWhere((e) => e.id == lastTurnedId).turnState, + TurnsState.done, + ); + + // --- Next round --------------------------------------------------------- + expect(runDrawOrNextRoundAction(gs), same(DrawOrNextRoundResult.success)); + expect(gs.round, 2); + expect(gs.roundState, RoundState.chooseInitiative); + expect( + gs.currentList.every((e) => e.turnState == TurnsState.notDone), + isTrue, + reason: 'turn states reset for the new round', + ); + expect( + gs.currentList.whereType<Character>().every( + (c) => c.characterState.initiative == 0, + ), + isTrue, + reason: 'regular characters must re-enter initiative each round', + ); + + // --- Round 2: initiative, draw, one turn, then round 3 ----------------- + gs.action(SetInitCommand('Blinkblade', 3, gameState: gs)); + gs.action(SetInitCommand('Banner Spear', 1, gameState: gs)); + expect(runDrawOrNextRoundAction(gs), same(DrawOrNextRoundResult.success)); + expect(gs.roundState, RoundState.playTurns); + expect(gs.currentList.whereType<Character>().map((c) => c.id), [ + 'Banner Spear', + 'Blinkblade', + ], reason: 'round 2 sorts by the new initiative values (1 before 3)'); + + final round2CurrentId = gs.currentList + .firstWhere((e) => e.turnState == TurnsState.current) + .id; + gs.action(TurnDoneCommand(round2CurrentId, gameState: gs)); + + expect(runDrawOrNextRoundAction(gs), same(DrawOrNextRoundResult.success)); + expect(gs.round, 3); + expect(gs.roundState, RoundState.chooseInitiative); + + checkSaveState(); + }); +} diff --git a/server/test/resource/action_handler_test.dart b/server/test/resource/action_handler_test.dart new file mode 100644 index 0000000..3137454 --- /dev/null +++ b/server/test/resource/action_handler_test.dart @@ -0,0 +1,215 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + }); + + group('ActionHandler', () { + group('getCurrent', () { + test('getCurrent returns the last executed command', () { + final gs = getIt<GameState>(); + final cmd = SetLevelCommand(3, null); + gs.action(cmd); + expect(gs.getCurrent(), same(cmd)); + gs.undo(); + }); + }); + + group('redo', () { + test('redo restores state after undo', () { + final gs = getIt<GameState>(); + // Two actions so gameSaveStates has enough entries for redo + gs.action(SetLevelCommand(2, null)); + gs.action(SetLevelCommand(5, null)); + expect(gs.level, 5); + gs.undo(); // back to level 2 + expect(gs.level, 2); + gs.redo(); // forward to level 5 + expect(gs.level, 5); + gs.undo(); + gs.undo(); + }); + + test('redo is a no-op when there is nothing to redo', () { + final gs = getIt<GameState>(); + gs.action(SetLevelCommand(4, null)); + // No undo performed, so redo should not crash and not change state + final levelBefore = gs.level; + gs.redo(); + expect(gs.level, levelBefore); + gs.undo(); + }); + + test('redo increments commandIndex', () { + final gs = getIt<GameState>(); + gs.action(SetLevelCommand(2, null)); + gs.action(SetLevelCommand(3, null)); + final indexAfterActions = gs.commandIndex; + gs.undo(); + expect(gs.commandIndex, indexAfterActions - 1); + gs.redo(); + expect(gs.commandIndex, indexAfterActions); + gs.undo(); + gs.undo(); + }); + }); + + group('redo list cleanup', () { + test('new action after undo clears the redo list', () { + final gs = getIt<GameState>(); + gs.action(SetLevelCommand(3, null)); + gs.action(SetLevelCommand(4, null)); + //final indexBefore = gs.commandIndex; + gs.undo(); // undo SetLevel(4), now commandIndex = indexBefore - 1 + // Do a new action — should clear SetLevel(4) from the redo list + gs.action(SetLevelCommand(5, null)); + // commands length should equal commandIndex + 1 (no redo entries) + expect(gs.commands.length - 1, gs.commandIndex); + expect(gs.commandDescriptions.length - 1, gs.commandIndex); + // Undo back to baseline + gs.undo(); + gs.undo(); + }); + }); + + group('maxUndo eviction', () { + test('commands and gameSaveStates beyond maxUndo are nulled', () { + final gs = getIt<GameState>(); + final maxUndo = gs.maxUndo; + final startIndex = gs.commandIndex; + + // Execute maxUndo + 1 commands to trigger eviction + for (int i = 0; i <= maxUndo; i++) { + gs.action(SetLevelCommand((i % 7) + 1, null)); + } + // After maxUndo+1 actions, the oldest command entry should be nulled + expect(gs.commands[startIndex + 1], isNull); + // gameSaveStates at oldest entry should also be nulled + expect(gs.gameSaveStates[startIndex + 1], isNull); + + // Undo back to near the start (only valid undo states) + for (int i = 0; i < maxUndo; i++) { + gs.undo(); + } + }); + }); + + group('getCurrent edge cases', () { + test( + 'getCurrent throws when there is no valid command at current index', + () { + final gs = getIt<GameState>(); + // Reset so commandIndex is -1 (no commands executed yet). + gs.commandIndex = -1; + gs.resetCommandHistory(); + // getCurrent accesses _commands[commandIndex] — either a RangeError + // (negative index) or TypeError (null-check on a null entry). Either + // way it must throw an Error so callers know to guard the call site. + expect(() => gs.getCurrent(), throwsA(isA<Error>())); + }, + ); + }); + + group('redo after maxUndo eviction', () { + test('redo from the oldest valid position does not crash', () { + final gs = getIt<GameState>(); + final maxUndo = gs.maxUndo; + + // Execute maxUndo + 1 commands so the oldest save state is evicted. + for (int i = 0; i <= maxUndo; i++) { + gs.action(SetLevelCommand((i % 7) + 1, null)); + } + + // Undo all the way to the eviction boundary: + // only the last maxUndo states are guaranteed non-null. + for (int i = 0; i < maxUndo; i++) { + gs.undo(); + } + // commandIndex is now at the boundary; gameSaveStates[commandIndex + 1] + // may be null (evicted). redo() must return early without crashing. + expect(() => gs.redo(), returnsNormally); + + // Restore state for other tests. + gs.undo(); + }); + }); + + group('add monster then undo', () { + test('undo after adding a monster removes it from the list', () { + final gs = getIt<GameState>(); + gs.clearList(); + gs.action( + AddMonsterCommand('Zealot', 1, false, gameState: getIt<GameState>()), + ); + expect(gs.currentList.any((e) => e.id == 'Zealot'), isTrue); + gs.undo(); + expect(gs.currentList.any((e) => e.id == 'Zealot'), isFalse); + }); + }); + + group('undo with commandIndex beyond gameSaveStates (Sentry regression)', () { + // Regression test for: + // ArgumentError: RangeError (length): Invalid value: Not in inclusive range 0..1079: 1080 + // ActionHandler.undo — crash when commandIndex >= gameSaveStates.length. + // + // Cause: in the server multiplayer path, Server.updateStateFromMessage sets + // commandIndex directly, then calls save(). After a + // resetState() (history cleared) a client that was ahead can send a message + // whose index ends up beyond the current gameSaveStates length after save(). + // A subsequent "undo" message from any client then crashes at + // _gameSaveStates[commandIndex] with no upper-bound guard. + test('does not crash when commandIndex >= gameSaveStates.length', () { + final gs = getIt<GameState>(); + + // Build a small amount of history. + gs.action(SetLevelCommand(3, null)); + gs.action(SetLevelCommand(4, null)); + + // Advance commandIndex past the end of gameSaveStates, simulating the + // server receiving a state message whose index was not matched by a save(). + gs.commandIndex = gs.gameSaveStates.length; // one beyond valid range + + // A client sends "undo" — the server calls undoState() → undo(). + // This must not throw a RangeError. + expect(() => gs.undo(), returnsNormally); + + // Restore a clean state for subsequent tests. + gs.commandIndex = -1; + gs.resetCommandHistory(); + }); + }); + + group('redo after connection reset in server mode', () { + // Regression test for: ArgumentError: RangeError (length): Invalid value: + // Valid value range is empty: -1 in ActionHandler.redo when a stale client + // sends "redo" after the server resets its command history on reconnect. + test('does not crash when commandIndex is -1 after connection reset', () { + final gs = getIt<GameState>(); + + // Build some history so gameSaveStates has an entry to retain. + gs.action(SetLevelCommand(3, null)); + + // Simulate the server-side connection-reset sequence: + // commandIndex → -1, command/description lists cleared, last save state kept. + gs.commandIndex = -1; + gs.resetCommandHistory(); + + // Stale client sends "redo" before it has re-synced with the server. + expect(() => gs.redo(), returnsNormally); + }); + }); + }); +} diff --git a/server/test/resource/game_methods_test.dart b/server/test/resource/game_methods_test.dart new file mode 100644 index 0000000..f960ca9 --- /dev/null +++ b/server/test/resource/game_methods_test.dart @@ -0,0 +1,1292 @@ +// ignore_for_file: avoid-late-keyword, no-empty-block, no-magic-number, avoid-non-null-assertion, prefer-first + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/models/character_class.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_perk_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_health_command.dart'; +import 'package:x_haven_server/core/commands/draw_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_character_level_command.dart'; +import 'package:x_haven_server/core/commands/set_init_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/commands/set_scenario_command.dart'; +import 'package:x_haven_server/core/commands/set_solo_command.dart'; +import 'package:x_haven_server/core/commands/show_ally_deck_command.dart'; +import 'package:x_haven_server/core/commands/turn_done_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() async { + await setUpGame(); + + group('GameMethods', () { + group('getTrapValue', () { + test('should return 2 + game level when level is 4', () { + // Act: Call the method we are testing. + SetLevelCommand(4, null).execute(); + String oldState = gameState.toString(); + final result = GameMethods.getTrapValue(); + + // Assert: Check if the result is what we expect. + expect(result, 6); + checkNoSideEffects([], oldState); + }); + + test('should return 2 when game level is 0', () { + SetLevelCommand(0, null).execute(); + String oldState = gameState.toString(); + // Act + final result = GameMethods.getTrapValue(); + + // Assert + expect(result, 2); + checkNoSideEffects([], oldState); + }); + + test('should return 9 when game level is 7', () { + SetLevelCommand(7, null).execute(); + String oldState = gameState.toString(); + // Act + final result = GameMethods.getTrapValue(); + + // Assert + expect(result, 9); + checkNoSideEffects([], oldState); + }); + + test('should bork when game level is out of bounds', () { + expect( + () => SetLevelCommand(77, null).execute(), + throwsA(isA<AssertionError>()), + ); + }); + + test('should bork when game level is out of bounds low', () { + expect( + () => SetLevelCommand(-77, null).execute(), + throwsA(isA<AssertionError>()), + ); + }); + }); + + group('getHazardValue', () { + test('should return 1 + ceil(level / 3) for Frosthaven', () { + getIt<Settings>().style = Style.frosthaven; + SetLevelCommand(0, null).execute(); + expect(GameMethods.getHazardValue(), 1); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(2, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(3, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(4, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(5, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(6, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getHazardValue(), 4); + }); + + test('should return floor(trapValue / 2) for Gloomhaven', () { + SetCampaignCommand("Gloomhaven").execute(); + getIt<Settings>().fhHazTerrainCalcInOGGloom = false; + + SetLevelCommand(0, null).execute(); + expect(GameMethods.getHazardValue(), 1); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getHazardValue(), 1); + SetLevelCommand(2, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(3, null).execute(); + expect(GameMethods.getHazardValue(), 2); + SetLevelCommand(4, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(5, null).execute(); + expect(GameMethods.getHazardValue(), 3); + SetLevelCommand(6, null).execute(); + expect(GameMethods.getHazardValue(), 4); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getHazardValue(), 4); + }); + }); + + group('getXPValue', () { + test('should return 4 + 2 * level', () { + SetLevelCommand(0, null).execute(); + expect(GameMethods.getXPValue(), 4); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getXPValue(), 6); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getXPValue(), 18); + }); + }); + + group('getCoinValue', () { + test('should return correct coin value for level', () { + SetLevelCommand(0, null).execute(); + expect(GameMethods.getCoinValue(), 2); + SetLevelCommand(1, null).execute(); + expect(GameMethods.getCoinValue(), 2); + SetLevelCommand(2, null).execute(); + expect(GameMethods.getCoinValue(), 3); + SetLevelCommand(3, null).execute(); + expect(GameMethods.getCoinValue(), 3); + SetLevelCommand(4, null).execute(); + expect(GameMethods.getCoinValue(), 4); + SetLevelCommand(5, null).execute(); + expect(GameMethods.getCoinValue(), 4); + SetLevelCommand(6, null).execute(); + expect(GameMethods.getCoinValue(), 5); + SetLevelCommand(7, null).execute(); + expect(GameMethods.getCoinValue(), 6); + }); + }); + + group('getRecommendedLevel', () { + test('should return 1 if no characters', () { + getIt<GameState>().clearList(); + + expect(GameMethods.getRecommendedLevel(), 1); + }); + + test('should calculate recommended level for multiple characters', () { + //getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + AddCharacterCommand( + 'Banner Spear', + 'Frosthaven', + 'Banner Spear', + 1, + ).execute(); + SetCharacterLevelCommand(3, 'Blinkblade').execute(); + SetCharacterLevelCommand(5, 'Banner Spear').execute(); + + expect(GameMethods.getRecommendedLevel(), 2); + }); + + test('should calculate recommended level for solo', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + SetCharacterLevelCommand(3, 'Blinkblade').execute(); + SetSoloCommand(true).execute(); + + expect(GameMethods.getRecommendedLevel(), 2); + }); + }); + + group('canDraw', () { + test('should return false if no characters', () { + getIt<GameState>().clearList(); + expect(GameMethods.canDraw(), isFalse); + }); + + test('should return true if noInit setting is true', () { + getIt<Settings>().noInit = true; + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + expect(GameMethods.canDraw(), isTrue); + }); + + test('should return false if a character has no initiative', () { + getIt<Settings>().noInit = false; + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + expect(GameMethods.canDraw(), isFalse); + }); + + test('should return true if all characters have initiative', () { + getIt<Settings>().noInit = false; + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + SetInitCommand( + 'Blinkblade', + 25, + gameState: getIt<GameState>(), + ).execute(); + expect(GameMethods.canDraw(), isTrue); + }); + }); + + //todo: + /*group('isInactiveForRule', () { + test('should return true if monster is inactive by rule', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt<GameState>()).execute(); + // In scenario 1, the Guard is inactive in round 1 + expect(GameMethods.isInactiveForRule('Guard'), isTrue); + }); + + test('should return false if monster is not inactive by rule', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt<GameState>()).execute(); + expect(GameMethods.isInactiveForRule('Guard'), isFalse); + }); + });*/ + + //todo: + /*group('getDeck', () { + test('should return the correct deck', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt<GameState>()).execute(); + final deck = GameMethods.getDeck('Guard'); + expect(deck, isNotNull); + expect(deck!.name, 'Guard'); + }); + + test('should return null if deck does not exist', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt<GameState>()).execute(); + final deck = GameMethods.getDeck('NonExistentDeck'); + expect(deck, isNull); + }); + });*/ + + group('getInitiative', () { + test('should return character initiative', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + SetInitCommand( + 'Blinkblade', + 35, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final character = getIt<GameState>().currentList.first as Character; + expect(GameMethods.getInitiative(character), 35); + checkNoSideEffects([], oldState); + }); + + //todo + /*test('should return monster initiative', () { + //getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt<GameState>()).execute(); + AddMonsterCommand(gameState: getIt<GameState>()).execute(); + DrawAbilityCardCommand().execute(); + final monster = getIt<GameState>() + .currentList + .firstWhere((m) => m is Monster) as Monster; + expect(GameMethods.getInitiative(monster), isNot(99)); + expect(GameMethods.getInitiative(monster), isNot(0)); + });*/ + }); + + group('getCharacterByName', () { + test('should return the correct character', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final character = GameMethods.getCharacterByName('Blinkblade'); + expect(character, isNotNull); + expect(character!.id, 'Blinkblade'); + checkNoSideEffects([], oldState); + }); + + test('should return null if character does not exist', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final character = GameMethods.getCharacterByName( + 'NonExistentCharacter', + ); + expect(character, isNull); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentCharacters', () { + test('should return a list of current characters', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final characters = GameMethods.getCurrentCharacters(); + expect(characters.length, 2); + expect(characters[1].id, 'Blinkblade'); + expect(characters[0].id, 'Banner Spear'); + checkNoSideEffects([], oldState); + }); + + test('should return an empty list if no characters', () { + getIt<GameState>().clearList(); + String oldState = gameState.toString(); + final characters = GameMethods.getCurrentCharacters(); + expect(characters, isEmpty); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentCharacter', () { + test('should return the character whose turn it is', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Banner Spear', 'Frosthaven', "", 1).execute(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + DrawCommand(gameState: getIt<GameState>()).execute(); + TurnDoneCommand( + 'Blinkblade', + gameState: getIt<GameState>(), + ).execute(); // It's now Banner Spear's turn + String oldState = gameState.toString(); + final character = GameMethods.getCurrentCharacter(); + expect(character, isNotNull); + expect(character!.id, 'Banner Spear'); + checkNoSideEffects([], oldState); + }); + + test('should return null if it is not a character turn', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); // Adds monsters + TurnDoneCommand( + getIt<GameState>().currentList.first.id, + gameState: getIt<GameState>(), + ).execute(); // It's now a monster's turn + String oldState = gameState.toString(); + final character = GameMethods.getCurrentCharacter(); + expect(character, isNull); + checkNoSideEffects([], oldState); + }); + }); + + group('getModifierDeck', () { + test('should return the monster modifier deck', () { + String oldState = gameState.toString(); + final deck = GameMethods.getModifierDeck('', getIt<GameState>()); + expect(deck, equals(getIt<GameState>().modifierDeck)); + checkNoSideEffects([], oldState); + }); + + test('should return the allies modifier deck', () { + String oldState = gameState.toString(); + final deck = GameMethods.getModifierDeck('allies', getIt<GameState>()); + expect(deck, equals(getIt<GameState>().modifierDeckAllies)); + checkNoSideEffects([], oldState); + }); + + test('should return a character modifier deck', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + String oldState = gameState.toString(); + final deck = GameMethods.getModifierDeck( + 'Blinkblade', + getIt<GameState>(), + ); + final character = getIt<GameState>().currentList.first as Character; + expect(deck, equals(character.characterState.modifierDeck)); + checkNoSideEffects([], oldState); + }); + }); + + group('canAddPerk', () { + test('should return true if perk can be added', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + String oldState = gameState.toString(); + final character = getIt<GameState>().currentList.first as Character; + expect(GameMethods.canAddPerk(character, 0), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if perk cannot be added', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + final character = getIt<GameState>().currentList.first as Character; + AddPerkCommand(character.id, 0).execute(); + String oldState = gameState.toString(); + expect(GameMethods.canAddPerk(character, 0), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('canRemovePerk', () { + test('should return true if perk can be removed', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + final character = getIt<GameState>().currentList.first as Character; + AddPerkCommand(character.id, 0).execute(); + String oldState = gameState.toString(); + expect(GameMethods.canRemovePerk(character, 0), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if perk cannot be removed', () { + getIt<GameState>().clearList(); + AddCharacterCommand( + 'Blinkblade', + 'Frosthaven', + 'Blinkblade', + 1, + ).execute(); + final character = getIt<GameState>().currentList.first as Character; + AddPerkCommand(character.id, 12).execute(); + AddPerkCommand(character.id, 13).execute(); + String oldState = gameState.toString(); + expect(GameMethods.canRemovePerk(character, 5), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('perkGfxIdToCardId', () { + test('should return the original gfx id if it is not a perk', () { + String oldState = gameState.toString(); + final id = GameMethods.perkGfxIdToCardId( + 'test', + PerkModel("", const [], const []), + 0, + ); + expect(id, 'test'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct card id for a perk', () { + String oldState = gameState.toString(); + final perk = PerkModel("", const [], const ['perks/test']); + final id = GameMethods.perkGfxIdToCardId('perks/test', perk, 0); + expect(id, 'P0'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct card id for a perk with two images', () { + String oldState = gameState.toString(); + final perk = PerkModel("", const [], const [ + 'perks/test', + 'perks/test2', + ]); + final id = GameMethods.perkGfxIdToCardId('perks/test2', perk, 0); + expect(id, 'P0-2'); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentCharacterAmount', () { + test('should return the number of characters', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + expect(GameMethods.getCurrentCharacterAmount(), 2); + checkNoSideEffects([], oldState); + }); + + test('should return 0 if no characters', () { + getIt<GameState>().clearList(); + String oldState = gameState.toString(); + expect(GameMethods.getCurrentCharacterAmount(), 0); + checkNoSideEffects([], oldState); + }); + }); + + group('getCurrentMonsters', () { + test('should return a list of current monsters', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final monsters = GameMethods.getCurrentMonsters(); + expect(monsters.length, 3); + expect(monsters[0].id, 'Zealot'); + expect(monsters[1].id, 'Chaos Demon'); + expect(monsters[2].id, 'Blood Tumor'); + checkNoSideEffects([], oldState); + }); + + test('should return an empty list if no monsters', () { + getIt<GameState>().clearList(); + String oldState = gameState.toString(); + final monsters = GameMethods.getCurrentMonsters(); + expect(monsters, isEmpty); + checkNoSideEffects([], oldState); + }); + }); + + /*group('getNextAvailableBnBStandee', () { + test('should return the next available standee number', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Buttons and Bugs').execute(); + //todo: + //SetScenarioCommand('#5 A Deeper Understanding', false, gameState: getIt<GameState>()).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + AddStandeeCommand(1, null, monster.id, MonsterType.normal, false, gameState: getIt<GameState>()) + .execute(); + final nextStandee = GameMethods.getNextAvailableBnBStandee(monster); + expect(nextStandee, 2); + }); + });*/ + + group('getRandomStandee', () { + test('should return a valid standee number', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt<GameState>().currentList.first as Monster; + final standee = GameMethods.getRandomStandee(monster); + expect(standee, isNot(0)); + expect(standee, lessThanOrEqualTo(monster.type.count)); + checkNoSideEffects([], oldState); + }); + }); + + group('getFigure', () { + test('should return a character', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + final figure = GameMethods.getFigure(null, 'Blinkblade'); + expect(figure, isNotNull); + expect(figure, isA<CharacterState>()); + checkNoSideEffects([], oldState); + }); + + test('should return a monster instance', () { + getIt<GameState>().clearList(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final figure = GameMethods.getFigure( + monster.id, + monster.monsterInstances.first.getId(), + ); + expect(figure, isNotNull); + expect(figure, isA<MonsterInstance>()); + checkNoSideEffects([], oldState); + }); + }); + + group('getFigureIdFromNr', () { + test('should return the figure id', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + AddStandeeCommand( + 1, + null, + monster.id, + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final id = GameMethods.getFigureIdFromNr(monster.id, 1); + expect(id, isNotNull); + expect(id, isNotEmpty); + checkNoSideEffects([], oldState); + }); + }); + + group('isObjectiveOrEscort', () { + test('should return true for Objective', () { + final cmd = AddCharacterCommand("Objective", "na", "whatever", 1); + String oldState = gameState.toString(); + expect( + GameMethods.isObjectiveOrEscort(cmd.character!.characterClass), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return true for Escort', () { + final cmd = AddCharacterCommand("Escort", "na", "whatever", 1); + String oldState = gameState.toString(); + expect( + GameMethods.isObjectiveOrEscort(cmd.character!.characterClass), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return false for other characters', () { + final cmd = AddCharacterCommand( + "Blinkblade", + "Frosthaven", + "whatever", + 1, + ); + String oldState = gameState.toString(); + expect( + GameMethods.isObjectiveOrEscort(cmd.character!.characterClass), + isFalse, + ); + checkNoSideEffects([], oldState); + }); + }); + + group('shouldShowAlliesDeck', () { + test('should return true if showAllyDeck setting is true', () { + String oldState = gameState.toString(); + getIt<Settings>().showAmdDeck = true; + ShowAllyDeckCommand().execute(); + expect(GameMethods.shouldShowAlliesDeck(), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if showAmdDeck setting is false', () { + String oldState = gameState.toString(); + getIt<Settings>().showAmdDeck = false; + expect(GameMethods.shouldShowAlliesDeck(), isFalse); + checkNoSideEffects([], oldState); + }); + + test('should return true if an ally monster is in play', () { + getIt<Settings>().showAmdDeck = true; + getIt<GameState>().clearList(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); // Adds monsters + AddMonsterCommand( + "Zealot", + 1, + true, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + expect(GameMethods.shouldShowAlliesDeck(), isTrue); + checkNoSideEffects([], oldState); + }); + }); + + group('canExpire', () { + test('should return true for conditions that expire', () { + String oldState = gameState.toString(); + expect(GameMethods.canExpire(Condition.strengthen), isTrue); + expect(GameMethods.canExpire(Condition.muddle), isTrue); + expect(GameMethods.canExpire(Condition.invisible), isTrue); + expect(GameMethods.canExpire(Condition.stun), isTrue); + expect(GameMethods.canExpire(Condition.disarm), isTrue); + expect(GameMethods.canExpire(Condition.immobilize), isTrue); + expect(GameMethods.canExpire(Condition.impair), isTrue); + expect(GameMethods.canExpire(Condition.chill), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for conditions that do not expire', () { + String oldState = gameState.toString(); + expect(GameMethods.canExpire(Condition.bane), isFalse); + expect(GameMethods.canExpire(Condition.poison), isFalse); + expect(GameMethods.canExpire(Condition.wound), isFalse); + expect(GameMethods.canExpire(Condition.regenerate), isFalse); + expect(GameMethods.canExpire(Condition.ward), isFalse); + expect(GameMethods.canExpire(Condition.brittle), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('isFrosthavenStyledEdition', () { + test('should return true for Frosthaven', () { + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Frosthaven'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return true for Buttons and Bugs', () { + String oldState = gameState.toString(); + expect( + GameMethods.isFrosthavenStyledEdition('Buttons and Bugs'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return true for Gloomhaven 2nd Edition', () { + String oldState = gameState.toString(); + expect( + GameMethods.isFrosthavenStyledEdition('Gloomhaven 2nd Edition'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return true for Mercenary Packs', () { + String oldState = gameState.toString(); + expect( + GameMethods.isFrosthavenStyledEdition('Mercenary Packs'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('should return false for Gloomhaven', () { + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Gloomhaven'), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('isFrosthavenStyle', () { + test('should return true for Frosthaven monster', () { + final monster = Monster('Ancient Artillery (FH)', 1, false); + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyle(monster.type), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for Gloomhaven monster', () { + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); // Adds monsters + String oldState = gameState.toString(); + final monster = Monster('Zealot', 1, false); + getIt<Settings>().style = Style.original; + expect(GameMethods.isFrosthavenStyle(monster.type), isFalse); + checkNoSideEffects([], oldState); + }); + + test('should return true if style is set to Frosthaven', () { + String oldState = gameState.toString(); + getIt<Settings>().style = Style.frosthaven; + expect(GameMethods.isFrosthavenStyle(null), isTrue); + checkNoSideEffects([], oldState); + }); + }); + + group('isCustomCampaign', () { + test('should return true for Crimson Scales', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('Crimson Scales'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return true for Trail of Ashes', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('Trail of Ashes'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return true for CCUG', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('CCUG'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for Frosthaven', () { + String oldState = gameState.toString(); + expect(GameMethods.isCustomCampaign('Frosthaven'), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('findNrFromScenarioName', () { + test('should return the scenario number from the name', () { + String oldState = gameState.toString(); + expect(GameMethods.findNrFromScenarioName('#1 '), 1); + expect( + GameMethods.findNrFromScenarioName('#10.0 A Sticky Situation'), + 10, + ); + expect(GameMethods.findNrFromScenarioName('#123 - Some Scenario'), 123); + checkNoSideEffects([], oldState); + }); + + test('should return null if no number is found', () { + String oldState = gameState.toString(); + expect(GameMethods.findNrFromScenarioName('Some Scenario'), isNull); + checkNoSideEffects([], oldState); + }); + }); + + group('isOgGloomEdition', () { + test('should return true for Gloomhaven', () { + SetCampaignCommand('Gloomhaven').execute(); + String oldState = gameState.toString(); + expect(GameMethods.isOgGloomEdition(), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false for Frosthaven', () { + SetCampaignCommand('Frosthaven').execute(); + String oldState = gameState.toString(); + expect(GameMethods.isOgGloomEdition(), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('hasLootDeck', () { + test('should return true if loot deck has cards', () { + getIt<GameState>().clearList(); + SetCampaignCommand('Frosthaven').execute(); + SetScenarioCommand( + '#0 Howling in the Snow', + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + //DrawLootCardCommand(gameState: getIt<GameState>()).execute(); + expect(GameMethods.hasLootDeck(), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if loot deck is empty', () { + //getIt<GameState>().clearLootDeck(); + SetCampaignCommand('Jaws of the Lion').execute(); + SetScenarioCommand( + '#5 A Deeper Understanding', + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + expect(GameMethods.hasLootDeck(), isFalse); + checkNoSideEffects([], oldState); + }); + + test('should return false if hideLootDeck setting is true', () { + String oldState = gameState.toString(); + getIt<Settings>().hideLootDeck = true; + expect(GameMethods.hasLootDeck(), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('getFactionCards', () { + test('should return the correct cards for Demons', () { + String oldState = gameState.toString(); + final cards = GameMethods.getFactionCards('Demons'); + expect(cards.length, 4); + expect(cards[0].gfx, 'Demons-perks/plus1any'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct cards for Merchant-Guild', () { + String oldState = gameState.toString(); + final cards = GameMethods.getFactionCards('Merchant-Guild'); + expect(cards.length, 4); + expect(cards[0].gfx, 'Merchant-Guild-perks/plus1curse'); + checkNoSideEffects([], oldState); + }); + + test('should return the correct cards for Military', () { + String oldState = gameState.toString(); + final cards = GameMethods.getFactionCards('Military'); + expect(cards.length, 4); + expect(cards[0].gfx, 'Military-perks/plus1strengthenally'); + checkNoSideEffects([], oldState); + }); + }); + + group('isCardInAnyCharacterDeck', () { + test('should return true if card is in a character deck', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + final character = getIt<GameState>().currentList.first as Character; + AddPerkCommand(character.id, 3).execute(); // Adds a +1 card + String oldState = gameState.toString(); + expect(GameMethods.isCardInAnyCharacterDeck('P3'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if card is not in any character deck', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', "", 1).execute(); + String oldState = gameState.toString(); + expect(GameMethods.isCardInAnyCharacterDeck('P3'), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('hasRetaliate', () { + test('should return true if monster has retaliate', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + "Flame Demon (BnB)", + 3, + false, + gameState: getIt<GameState>(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Flame Demon (BnB)", + MonsterType.boss, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt<GameState>().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasRetaliate(monster, instance), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if monster does not have retaliate', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + "Black Sludge", + 3, + false, + gameState: getIt<GameState>(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Black Sludge", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt<GameState>().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasRetaliate(monster, instance), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('hasShield', () { + test('should return true if monster has shield', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + "Black Sludge", + 3, + false, + gameState: getIt<GameState>(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Black Sludge", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt<GameState>().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasShield(monster, instance), isTrue); + checkNoSideEffects([], oldState); + }); + + test('should return false if monster does not have shield', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + "Zealot", + 1, + false, + gameState: getIt<GameState>(), + ).execute(); // Monster without shield + AddStandeeCommand( + 1, + null, + "Zealot", + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final monster = getIt<GameState>().currentList.first as Monster; + final instance = monster.monsterInstances.first; + expect(GameMethods.hasShield(monster, instance), isFalse); + checkNoSideEffects([], oldState); + }); + }); + + group('canDraw - dead character bypasses initiative check', () { + test( + 'dead character (health=0) does not block draw even with no init', + () { + getIt<GameState>().clearList(); + getIt<Settings>().noInit = false; + AddCharacterCommand('Blinkblade', 'Frosthaven', null, 1).execute(); + // Kill the character so health = 0 + final character = getIt<GameState>().currentList.first as Character; + // Reduce health to 0 via ChangeHealthCommand + ChangeHealthCommand( + -1000, + 'Blinkblade', + 'Blinkblade', + gameState: getIt<GameState>(), + ).execute(); + expect(character.characterState.health, 0); + // Dead character with 0 initiative should NOT block the draw + expect(GameMethods.canDraw(), isTrue); + }, + ); + }); + + group('getInitiative - inactive monster', () { + test('inactive monster returns initiative 99', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + // Monster is inactive by default (isActive = false until ability drawn) + expect(monster.isActive, isFalse); + String oldState = gameState.toString(); + expect(GameMethods.getInitiative(monster), 99); + checkNoSideEffects([], oldState); + }); + }); + + group('summonDoesNotDie', () { + test('Glacial Torrent Glacier does not die', () { + String oldState = gameState.toString(); + expect( + GameMethods.summonDoesNotDie('Glacial Torrent', 'Glacier'), + isTrue, + ); + checkNoSideEffects([], oldState); + }); + + test('D.O.M.E. Barrier does not die', () { + String oldState = gameState.toString(); + expect(GameMethods.summonDoesNotDie('D.O.M.E.', 'Barrier'), isTrue); + checkNoSideEffects([], oldState); + }); + + test('arbitrary owner and id returns false', () { + String oldState = gameState.toString(); + expect( + GameMethods.summonDoesNotDie('Blinkblade', 'Jade Falcon'), + isFalse, + ); + checkNoSideEffects([], oldState); + }); + }); + + group('getFigure - character summon lookup', () { + test('returns summon instance when found via character ownerId', () { + getIt<GameState>().clearList(); + AddCharacterCommand('Blinkblade', 'Frosthaven', null, 1).execute(); + final character = getIt<GameState>().currentList.first as Character; + // Add a summon to the character + final summonData = SummonData( + 1, + 'Jade Falcon', + 3, + 2, + 2, + 0, + 'Jade Falcon', + ); + AddStandeeCommand( + 1, + summonData, + 'Blinkblade', + MonsterType.normal, + true, + gameState: getIt<GameState>(), + ).execute(); + + expect(character.characterState.summonList, isNotEmpty); + final summon = character.characterState.summonList.first; + final figureId = summon.getId(); + + String oldState = gameState.toString(); + final figure = GameMethods.getFigure('Blinkblade', figureId); + expect(figure, isNotNull); + expect(figure, isA<MonsterInstance>()); + checkNoSideEffects([], oldState); + }); + }); + + group('isFrosthavenStyledEdition - Solo edition', () { + test('Solo with Frosthaven scenario number is frosthaven styled', () { + // Directly set the scenario string to avoid SetScenarioCommand's loot-deck lookup + gameState.scenario = '#1 A Town Aflame'; + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Solo'), isTrue); + checkNoSideEffects(['scenario'], oldState); + }); + + test( + 'Solo with #19 scenario is NOT frosthaven styled (Forgotten Circles)', + () { + gameState.scenario = '#19 Forgotten Circles'; + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Solo'), isFalse); + checkNoSideEffects(['scenario'], oldState); + }, + ); + + test( + 'Solo with scenario not in 1-100 range is not frosthaven styled', + () { + gameState.scenario = '#200 Some Scenario'; + String oldState = gameState.toString(); + expect(GameMethods.isFrosthavenStyledEdition('Solo'), isFalse); + checkNoSideEffects(['scenario'], oldState); + }, + ); + }); + + group('hasShield - boss type', () { + test('boss type standee checks boss attribute for shield', () { + getIt<GameState>().clearList(); + // Flame Demon (BnB) is a boss with retaliate; use it to test boss path + AddMonsterCommand( + 'Flame Demon (BnB)', + 3, + false, + gameState: getIt<GameState>(), + ).execute(); + AddStandeeCommand( + 1, + null, + 'Flame Demon (BnB)', + MonsterType.boss, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + final instance = monster.monsterInstances.first; + // Boss path is exercised; result depends on actual data, just verify no crash + expect(GameMethods.hasShield(monster, instance), isA<bool>()); + expect(GameMethods.hasRetaliate(monster, instance), isA<bool>()); + }); + }); + + group('getNextAvailableBnBStandee', () { + test('returns next available standee number when one is taken', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + String oldState = gameState.toString(); + final next = GameMethods.getNextAvailableBnBStandee(monster); + // Standee 1 is taken; next available should be 2 + expect(next, 2); + checkNoSideEffects([], oldState); + }); + + test('returns 0 when all standees are taken', () { + getIt<GameState>().clearList(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + final monster = getIt<GameState>().currentList.first as Monster; + for (int i = 1; i <= monster.type.count; i++) { + AddStandeeCommand( + i, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + } + String oldState = gameState.toString(); + final next = GameMethods.getNextAvailableBnBStandee(monster); + expect(next, 0); + checkNoSideEffects([], oldState); + }); + }); + }); +} diff --git a/server/test/resource/line_builder/line_builder_test.dart b/server/test/resource/line_builder/line_builder_test.dart new file mode 100644 index 0000000..c6aece7 --- /dev/null +++ b/server/test/resource/line_builder/line_builder_test.dart @@ -0,0 +1,67 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/line_builder/line_builder.dart'; + +// Only the pure-logic parts of the reference `line_builder_test.dart` are +// ported: the widget/metrics tests (`createLines`, `getTopPaddingForStyle`) +// depend on Flutter classes and the unported rendering code, so they are +// skipped until the Phase 4 web client re-implements the rendering. + +void main() { + // ── isElement ───────────────────────────────────────────────────────────── + + group('LineBuilder.isElement', () { + test('"fire" is an element', () { + expect(LineBuilder.isElement('fire'), isTrue); + }); + + test('"air" is an element', () { + expect(LineBuilder.isElement('air'), isTrue); + }); + + test('"earth" is an element', () { + expect(LineBuilder.isElement('earth'), isTrue); + }); + + test('"ice" is an element', () { + expect(LineBuilder.isElement('ice'), isTrue); + }); + + test('"dark" is an element', () { + expect(LineBuilder.isElement('dark'), isTrue); + }); + + test('"light" is an element', () { + expect(LineBuilder.isElement('light'), isTrue); + }); + + test('"any" is an element', () { + expect(LineBuilder.isElement('any'), isTrue); + }); + + test('string containing element name returns true', () { + // e.g. "fire_fh" contains "fire" + expect(LineBuilder.isElement('fire_fh'), isTrue); + expect(LineBuilder.isElement('dark_half'), isTrue); + }); + + test('"attack" is not an element', () { + expect(LineBuilder.isElement('attack'), isFalse); + }); + + test('"move" is not an element', () { + expect(LineBuilder.isElement('move'), isFalse); + }); + + test('"poison" is not an element', () { + expect(LineBuilder.isElement('poison'), isFalse); + }); + + test('empty string is not an element', () { + expect(LineBuilder.isElement(''), isFalse); + }); + + test('"heal" is not an element', () { + expect(LineBuilder.isElement('heal'), isFalse); + }); + }); +} diff --git a/server/test/resource/line_builder/stat_applier_test.dart b/server/test/resource/line_builder/stat_applier_test.dart new file mode 100644 index 0000000..c87e81b --- /dev/null +++ b/server/test/resource/line_builder/stat_applier_test.dart @@ -0,0 +1,284 @@ +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_monster_command.dart'; +import 'package:x_haven_server/core/commands/add_standee_command.dart'; +import 'package:x_haven_server/core/commands/set_campaign_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/line_builder/stat_applier.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import '../../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + SetLevelCommand(1, null).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + AddMonsterCommand( + 'Zealot', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + // Zealot level 1: normal attack=2 move=2 range=0, elite attack=3 move=2 range=0 + + Monster zealot() => + getIt<GameState>().currentList.firstWhere((e) => e.id == 'Zealot') + as Monster; + + // ── plain text – no formulas ────────────────────────────────────────────── + + group('StatApplier.applyMonsterStats – plain text', () { + test('line with no formula is returned unchanged', () { + final result = StatApplier.applyMonsterStats( + 'Move 3', + '', + zealot(), + false, + ); + expect(result, equals(['Move 3'])); + }); + + test('line with pure text and token name unchanged', () { + final result = StatApplier.applyMonsterStats( + '%attack%', + '', + zealot(), + false, + ); + expect(result, equals(['%attack%'])); + }); + + test('single digit with no preceding token is treated as plain text', () { + // "3" alone at position 0 is a plain number; no token → calculateFormula("3")=3 + // but length must be >2 or formula must have lastToken; "3" alone is length 1 → not applied + final result = StatApplier.applyMonsterStats('3', '', zealot(), false); + expect(result, equals(['3'])); + }); + }); + + // ── forceShowAll=false with no standees ────────────────────────────────── + + group('StatApplier.applyMonsterStats – no standees (forceShowAll=false)', () { + test('%attack% +0 unchanged when no standees and forceShowAll=false', () { + // showNormal=false, showElite=false → line returned as-is + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + false, + ); + expect(result, equals(['%attack% +0'])); + }); + + test('%move% +1 unchanged when no standees and forceShowAll=false', () { + final result = StatApplier.applyMonsterStats( + '%move% +1', + '', + zealot(), + false, + ); + expect(result, equals(['%move% +1'])); + }); + }); + + // ── forceShowAll=true: attack formula ───────────────────────────────────── + + group('StatApplier.applyMonsterStats – forceShowAll attack', () { + test('%attack% +0 with forceShowAll splits into multiple results', () { + // normal attack=2, elite attack=3; formula "+0" → normal=2, elite=3 + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + true, + ); + expect(result.length, greaterThan(1)); + }); + + test('normal result contains the computed normal attack value', () { + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + true, + ); + // First string contains "%attack% 2/" (the normal result) + expect(result.first, contains('2')); + }); + + test('elite result contains the computed elite attack value', () { + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + true, + ); + // Second string is the elite part starting with "!" + final elite = result.firstWhere((s) => s.startsWith('!')); + expect(elite, contains('3')); + }); + + test('%attack% +1 adds 1 to both normal and elite values', () { + // normal=2+1=3, elite=3+1=4 + final result = StatApplier.applyMonsterStats( + '%attack% +1', + '', + zealot(), + true, + ); + expect(result.first, contains('3')); + final elite = result.firstWhere((s) => s.startsWith('!')); + expect(elite, contains('4')); + }); + + test('%attack% -1 subtracts 1 (clamps to 0 if negative)', () { + // normal=2-1=1, elite=3-1=2 + final result = StatApplier.applyMonsterStats( + '%attack% -1', + '', + zealot(), + true, + ); + expect(result.first, contains('1')); + final elite = result.firstWhere((s) => s.startsWith('!')); + expect(elite, contains('2')); + }); + }); + + // ── forceShowAll=true: move formula ────────────────────────────────────── + + group('StatApplier.applyMonsterStats – forceShowAll move', () { + test('%move% +0 yields Zealot move value (2)', () { + final result = StatApplier.applyMonsterStats( + '%move% +0', + '', + zealot(), + true, + ); + expect(result.first, contains('2')); + }); + + test('%move% +2 yields Zealot move+2 (4) for both', () { + // normal move=2+2=4, elite move=2+2=4 + final result = StatApplier.applyMonsterStats( + '%move% +2', + '', + zealot(), + true, + ); + expect(result.first, contains('4')); + }); + }); + + // ── with standees present (forceShowAll=false) ─────────────────────────── + + group('StatApplier.applyMonsterStats – with actual standees', () { + test('normal standee present → shows normal stat', () { + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.normal, + false, + gameState: getIt<GameState>(), + ).execute(); + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + false, + ); + // showNormal=true, showElite=false + expect(result.first, contains('2')); + // No elite part + expect(result.every((s) => !s.contains('3')), isTrue); + getIt<GameState>().undo(); + }); + + test('elite standee present → shows both normal and elite stat', () { + AddStandeeCommand( + 1, + null, + 'Zealot', + MonsterType.elite, + false, + gameState: getIt<GameState>(), + ).execute(); + final result = StatApplier.applyMonsterStats( + '%attack% +0', + '', + zealot(), + false, + ); + // showElite=true → split output with both values + expect(result.length, greaterThan(1)); + expect(result.any((s) => s.contains('3')), isTrue); + getIt<GameState>().undo(); + }); + }); + + // ── formula without preceding token ────────────────────────────────────── + + group('StatApplier.applyMonsterStats – standalone formula', () { + test('C+L formula (≥3 chars, no token) is evaluated', () { + // With level=1 and 0 characters (C clamped to 2): C+L = 2+1 = 3 + final result = StatApplier.applyMonsterStats( + 'C+L health', + '', + zealot(), + false, + ); + expect(result.first, contains('3')); + }); + + test('plain number ≥3 digits is evaluated as formula', () { + // "100" is 3 chars and contains only digits; calculateFormula("100")=100 + final result = StatApplier.applyMonsterStats( + '100 damage', + '', + zealot(), + false, + ); + expect(result.first, contains('100')); + }); + }); + + // ── shield from attribute ───────────────────────────────────────────────── + + group('StatApplier.applyMonsterStats – shield token', () { + setUp(() { + getIt<GameState>().clearList(); + SetLevelCommand(1, null).execute(); + SetCampaignCommand('Jaws of the Lion').execute(); + // Black Sludge has %shield% 1 in both normal and elite at level 1 + AddMonsterCommand( + 'Black Sludge', + 1, + false, + gameState: getIt<GameState>(), + ).execute(); + }); + + Monster blackSludge() => + getIt<GameState>().currentList.firstWhere((e) => e.id == 'Black Sludge') + as Monster; + + test('%shield% +0 with Black Sludge yields shield value 1', () { + final result = StatApplier.applyMonsterStats( + '%shield% +0', + '', + blackSludge(), + true, + ); + expect(result.first, contains('1')); + }); + }); +} diff --git a/server/test/resource/modifier_deck_test.dart b/server/test/resource/modifier_deck_test.dart new file mode 100644 index 0000000..bb5daa0 --- /dev/null +++ b/server/test/resource/modifier_deck_test.dart @@ -0,0 +1,175 @@ +// ignore_for_file: avoid-late-keyword, no-empty-block, no-magic-number, avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/amd_imbue1_command.dart'; +import 'package:x_haven_server/core/commands/amd_imbue2_command.dart'; +import 'package:x_haven_server/core/commands/amd_remove_imbue_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_bless_command.dart'; +import 'package:x_haven_server/core/commands/change_stat_commands/change_curse_command.dart'; +import 'package:x_haven_server/core/commands/draw_modifier_card_command.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; + +import '../command/test_helpers.dart'; + +void main() { + late GameState gameState; + + setUpAll(() async { + // Registers the core singletons (save store, game data, settings) once; + // each test still gets a fresh [GameState] below, mirroring the + // reference app's per-test `makeGameAndSettings()`. + await setUpGame(); + }); + + setUp(() { + gameState = GameState(); + gameState.init(); + }); + + ModifierDeck deck() => gameState.modifierDeck; + + // ── draw() ──────────────────────────────────────────────────────────────── + + group('ModifierDeck.draw', () { + test('drawing multiply card sets needsShuffle', () { + bool foundMultiply = false; + for (int i = 0; i < 50; i++) { + if (deck().drawPileIsEmpty) break; + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + if (deck().discardPileContents.any( + (c) => c.type == CardType.multiply, + )) { + foundMultiply = true; + break; + } + } + if (foundMultiply) { + expect(deck().needsShuffle, isTrue); + } + }); + + test('drawing a bless card decrements bless count', () { + gameState.action(ChangeBlessCommand(1, '', '', gameState: gameState)); + gameState.action(ChangeBlessCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('bless'), 2); + + bool drewBless = false; + for (int i = 0; i < 30; i++) { + if (deck().drawPileIsEmpty) break; + final before = deck().getRemovable('bless'); + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + if (deck().getRemovable('bless') < before) { + drewBless = true; + break; + } + } + if (drewBless) { + expect(deck().getRemovable('bless'), lessThan(2)); + } + }); + + test('drawing all cards triggers reshuffle when drawPile is empty', () { + final initialSize = deck().drawPileSize; + for (int i = 0; i < initialSize; i++) { + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + } + expect(deck().drawPileIsEmpty, isTrue); + gameState.action(DrawModifierCardCommand('', gameState: gameState)); + expect(deck().discardPileSize, greaterThan(0)); + }); + }); + + // ── setImbue1 / setImbue2 / resetImbue ─────────────────────────────────── + + group('ModifierDeck imbue', () { + test('setImbue1 sets imbuement to 1 and adds imbue cards', () { + gameState.action(AMDImbue1Command(gameState: gameState)); + expect(deck().imbuement, 1); + final hasImbueCards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue'), + ); + expect(hasImbueCards, isTrue); + }); + + test('setImbue2 sets imbuement to 2 and adds imbue2 cards', () { + gameState.action(AMDImbue2Command(gameState: gameState)); + expect(deck().imbuement, 2); + final hasImbue2Cards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue2'), + ); + expect(hasImbue2Cards, isTrue); + }); + + test('setImbue2 from scratch also applies setImbue1 first', () { + expect(deck().imbuement, 0); + gameState.action(AMDImbue2Command(gameState: gameState)); + expect(deck().imbuement, 2); + final hasImbueCards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue'), + ); + expect(hasImbueCards, isTrue); + }); + + test('resetImbue from imbue1 removes imbue cards and resets to 0', () { + gameState.action(AMDImbue1Command(gameState: gameState)); + expect(deck().imbuement, 1); + gameState.action(AMDRemoveImbueCommand(gameState: gameState)); + expect(deck().imbuement, 0); + final hasImbueCards = deck().drawPileContents.toList().any( + (c) => c.gfx.startsWith('imbue'), + ); + expect(hasImbueCards, isFalse); + }); + + test('resetImbue from imbue2 restores minus2 and plus0 cards', () { + gameState.action(AMDImbue2Command(gameState: gameState)); + expect(deck().imbuement, 2); + gameState.action(AMDRemoveImbueCommand(gameState: gameState)); + expect(deck().imbuement, 0); + final hasMinus2 = deck().drawPileContents.toList().any( + (c) => c.gfx == 'minus2', + ); + expect(hasMinus2, isTrue); + }); + + test('resetImbue is a no-op when imbuement is already 0', () { + expect(deck().imbuement, 0); + final drawSizeBefore = deck().drawPileSize; + gameState.action(AMDRemoveImbueCommand(gameState: gameState)); + expect(deck().imbuement, 0); + expect(deck().drawPileSize, drawSizeBefore); + }); + }); + + // ── _handleRemovableCards ───────────────────────────────────────────────── + + group('ModifierDeck removable cards', () { + test('adding a curse increases curse count and inserts card', () { + final before = deck().getRemovable('curse'); + gameState.action(ChangeCurseCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('curse'), before + 1); + final curseInDeck = deck().drawPileContents + .toList() + .where((c) => c.gfx == 'curse') + .length; + expect(curseInDeck, before + 1); + }); + + test( + 'removing a curse decreases curse count and removes card from deck', + () { + gameState.action(ChangeCurseCommand(1, '', '', gameState: gameState)); + gameState.action(ChangeCurseCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('curse'), 2); + gameState.action(ChangeCurseCommand(-1, '', '', gameState: gameState)); + expect(deck().getRemovable('curse'), 1); + }, + ); + + test('adding a bless increases bless count in deck', () { + final before = deck().getRemovable('bless'); + gameState.action(ChangeBlessCommand(1, '', '', gameState: gameState)); + expect(deck().getRemovable('bless'), before + 1); + }); + }); +} diff --git a/server/test/resource/stat_calculator_test.dart b/server/test/resource/stat_calculator_test.dart new file mode 100644 index 0000000..f80c0fb --- /dev/null +++ b/server/test/resource/stat_calculator_test.dart @@ -0,0 +1,174 @@ +// ignore_for_file: avoid-late-keyword, no-empty-block, no-magic-number, avoid-non-null-assertion + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/commands/add_character_command.dart'; +import 'package:x_haven_server/core/commands/set_level_command.dart'; +import 'package:x_haven_server/core/stat_calculator.dart'; +import 'package:x_haven_server/core/state/game_state.dart'; +import 'package:x_haven_server/core/service_locator.dart'; + +import '../command/test_helpers.dart'; + +void main() { + setUpAll(() async { + await setUpGame(); + }); + + setUp(() { + getIt<GameState>().clearList(); + SetLevelCommand(1, null).execute(); + }); + + // ── eval / Parser ──────────────────────────────────────────────────────── + + group('StatCalculator.eval', () { + test('parses a plain integer string', () { + expect(StatCalculator.eval('5'), 5); + }); + + test('parses addition', () { + expect(StatCalculator.eval('3+2'), 5); + }); + + test('parses subtraction', () { + expect(StatCalculator.eval('7-3'), 4); + }); + + test('parses multiplication with *', () { + expect(StatCalculator.eval('3*4'), 12); + }); + + test('parses multiplication with x', () { + // 'x' is an alternative multiplication operator + expect(StatCalculator.eval('3x4'), 12); + }); + + test('parses division with / (ceiling)', () { + // 7 / 2 = 3.5 → ceil → 4 + expect(StatCalculator.eval('7/2'), 4); + }); + + test('parses division with d (floor)', () { + // 7 d 2 = 3.5 → floor → 3 + expect(StatCalculator.eval('7d2'), 3); + }); + + test('parses parenthesised expression', () { + expect(StatCalculator.eval('(2+3)*4'), 20); + }); + + test('parses unary minus', () { + // Unary minus applied to a number; result is negative + // StatCalculator stores as int so -5 + expect(StatCalculator.eval('0-5'), -5); + }); + + test('returns null for malformed expression', () { + expect(StatCalculator.eval('abc'), isNull); + }); + + test('returns null for expression with trailing characters', () { + // '5 extra' has trailing non-parseable chars after the number + expect(StatCalculator.eval('5extra'), isNull); + }); + + test('parses condition less-than (true → 1)', () { + expect(StatCalculator.eval('2<3'), 1); + }); + + test('parses condition less-than (false → 0)', () { + expect(StatCalculator.eval('3<2'), 0); + }); + + test('parses condition greater-than (true → 1)', () { + expect(StatCalculator.eval('5>4'), 1); + }); + + test('parses condition greater-than (false → 0)', () { + expect(StatCalculator.eval('1>2'), 0); + }); + + test('parses condition equals (true → 1)', () { + expect(StatCalculator.eval('4=4'), 1); + }); + + test('parses condition equals (false → 0)', () { + expect(StatCalculator.eval('4=5'), 0); + }); + + test('ceil division: exact division gives no rounding', () { + expect(StatCalculator.eval('6/2'), 3); + }); + + test('floor division: exact division gives no rounding', () { + expect(StatCalculator.eval('6d2'), 3); + }); + + test('operator precedence: multiplication before addition', () { + // 2 + 3 * 4 = 14 only if * has higher precedence + // The parser is left-to-right for same level; + and * are different levels + // parseTerm handles * so it should be: 2 + (3*4) = 14 + expect(StatCalculator.eval('2+3*4'), 14); + }); + }); + + // ── calculateFormula ──────────────────────────────────────────────────── + + group('StatCalculator.calculateFormula', () { + test('returns int directly when passed an int', () { + expect(StatCalculator.calculateFormula(7), 7); + }); + + test('substitutes C with character count (clamped to 2 minimum)', () { + // No characters added → count = 0, clamped to 2 + expect(StatCalculator.calculateFormula('C'), 2); + }); + + test('substitutes C with actual character count when ≥ 2', () { + AddCharacterCommand('Blinkblade', 'Frosthaven', null, 1).execute(); + AddCharacterCommand('Banner Spear', 'Frosthaven', null, 1).execute(); + AddCharacterCommand('Hail', 'Mercenary Packs', null, 1).execute(); + // 3 characters → C = 3 + expect(StatCalculator.calculateFormula('C'), 3); + }); + + test('substitutes L with current level', () { + SetLevelCommand(4, null).execute(); + expect(StatCalculator.calculateFormula('L'), 4); + }); + + test('evaluates compound formula with C and L', () { + // With 0 chars (C=2) and level 3: C+L = 2+3 = 5 + SetLevelCommand(3, null).execute(); + expect(StatCalculator.calculateFormula('C+L'), 5); + }); + + test('returns null for invalid formula string', () { + expect(StatCalculator.calculateFormula('??'), isNull); + }); + }); + + // ── evaluateCondition ──────────────────────────────────────────────────── + + group('StatCalculator.evaluateCondition', () { + test('returns true when formula evaluates to 1', () { + // '1' evaluates to 1 → true + expect(StatCalculator.evaluateCondition('1'), isTrue); + }); + + test('returns false when formula evaluates to 0', () { + expect(StatCalculator.evaluateCondition('0'), isFalse); + }); + + test('returns false when formula evaluates to something other than 1', () { + expect(StatCalculator.evaluateCondition('2'), isFalse); + }); + + test('evaluates condition expression correctly', () { + // '2<3' → 1 → true + expect(StatCalculator.evaluateCondition('2<3'), isTrue); + // '3<2' → 0 → false + expect(StatCalculator.evaluateCondition('3<2'), isFalse); + }); + }); +} diff --git a/server/test/resource/ui_utils_test.dart b/server/test/resource/ui_utils_test.dart new file mode 100644 index 0000000..fc44c02 --- /dev/null +++ b/server/test/resource/ui_utils_test.dart @@ -0,0 +1,48 @@ +// ignore_for_file: no-magic-number + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/ui_utils.dart'; + +import '../command/test_helpers.dart'; + +/// The reference `ui_utils_test.dart` has no `reducePowerEnabled` group — +/// its groups (`hasGHVersion`, text-style helpers, dialog/toast widget +/// functions) all exercise unported widget code. This file instead covers +/// the single ported `ui_utils` function, `reducePowerEnabled`, mirroring +/// the reference implementation's documented semantics. +void main() { + setUpAll(() async { + await setUpGame(); + }); + + // ── reducePowerEnabled ──────────────────────────────────────────────────── + + group('reducePowerEnabled', () { + test('returns false by default (PowerMode.normal)', () { + expect(reducePowerEnabled(), isFalse); + }); + + test('returns true when powerMode is reducePower', () { + getIt<Settings>().powerMode = PowerMode.reducePower; + expect(reducePowerEnabled(), isTrue); + getIt<Settings>().powerMode = PowerMode.normal; + }); + + test('returns false for dimWhenIdle (top tier only)', () { + getIt<Settings>().powerMode = PowerMode.dimWhenIdle; + expect(reducePowerEnabled(), isFalse); + getIt<Settings>().powerMode = PowerMode.normal; + }); + + test('honors an explicitly passed Settings instance', () { + final settings = Settings(); + settings.powerMode = PowerMode.reducePower; + expect(reducePowerEnabled(settings: settings), isTrue); + settings.powerMode = PowerMode.normal; + expect(reducePowerEnabled(settings: settings), isFalse); + }); + }); +} diff --git a/server/test/smoke_test.dart b/server/test/smoke_test.dart index b9a4263..2ac745e 100644 --- a/server/test/smoke_test.dart +++ b/server/test/smoke_test.dart @@ -14,13 +14,16 @@ class _MessageReader { final StreamIterator<Map<String, dynamic>> _iterator; _MessageReader(this.channel) - : _iterator = StreamIterator( - channel.stream - .map((Object? raw) => jsonDecode(raw as String) as Map<String, dynamic>)); + : _iterator = StreamIterator( + channel.stream.map( + (Object? raw) => jsonDecode(raw as String) as Map<String, dynamic>, + ), + ); Future<Map<String, dynamic>> next() async { - final advanced = - await _iterator.moveNext().timeout(const Duration(seconds: 5)); + final advanced = await _iterator.moveNext().timeout( + const Duration(seconds: 5), + ); if (!advanced) { fail('connection closed before the expected message arrived'); } @@ -43,7 +46,8 @@ void main() { WebSocketChannel connect() { final channel = WebSocketChannel.connect( - Uri.parse('ws://localhost:${server.port}/ws')); + Uri.parse('ws://localhost:${server.port}/ws'), + ); addTearDown(() => unawaited(channel.sink.close())); return channel; } @@ -51,8 +55,9 @@ void main() { test('serves a stub page at / when the static dir is missing', () async { final client = HttpClient(); addTearDown(client.close); - final request = - await client.getUrl(Uri.parse('http://localhost:${server.port}/')); + final request = await client.getUrl( + Uri.parse('http://localhost:${server.port}/'), + ); final response = await request.close(); expect(response.statusCode, 200); final body = await response.transform(utf8.decoder).join(); @@ -62,8 +67,9 @@ void main() { test('answers healthz', () async { final client = HttpClient(); addTearDown(client.close); - final request = - await client.getUrl(Uri.parse('http://localhost:${server.port}/healthz')); + final request = await client.getUrl( + Uri.parse('http://localhost:${server.port}/healthz'), + ); final response = await request.close(); expect(response.statusCode, 200); final body = jsonDecode(await response.transform(utf8.decoder).join()); |
