test: audit and strengthen legacy test suite

This commit is contained in:
2026-07-25 06:54:18 +00:00
parent 46ae79dbe7
commit 7ed1b5df7f
27 changed files with 422 additions and 654 deletions
-2
View File
@@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=clock.test.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"clock.test.d.ts","sourceRoot":"","sources":["clock.test.ts"],"names":[],"mappings":""}
-44
View File
@@ -1,44 +0,0 @@
import { describe, expect, it } from 'vitest';
import { ManualClock, StepClock } from '../src/time/Clock.js';
describe('ManualClock', () => {
it('returns current time without advancing', () => {
const clock = new ManualClock(1000);
expect(clock.nowMs()).toBe(1000);
expect(clock.nowMs()).toBe(1000);
});
it('advances with sleep and manual advance', async () => {
const clock = new ManualClock(0);
await clock.sleepMs(250);
expect(clock.nowMs()).toBe(250);
clock.advanceMs(750);
expect(clock.nowMs()).toBe(1000);
});
it('can set time explicitly', () => {
const clock = new ManualClock(10);
clock.setMs(5000);
expect(clock.nowMs()).toBe(5000);
});
});
describe('StepClock', () => {
it('advances on each nowMs call', () => {
const clock = new StepClock(100, 0);
expect(clock.nowMs()).toBe(100);
expect(clock.nowMs()).toBe(200);
expect(clock.nowMs()).toBe(300);
});
it('advances with sleep', async () => {
const clock = new StepClock(50, 1000);
await clock.sleepMs(200);
expect(clock.nowMs()).toBe(1250);
});
it('advances manually', () => {
const clock = new StepClock(10, 0);
clock.advanceMs(50);
expect(clock.nowMs()).toBe(60);
});
it('rejects non-positive step', () => {
expect(() => new StepClock(0)).toThrow('stepMs must be positive');
expect(() => new StepClock(-5)).toThrow('stepMs must be positive');
});
});
//# sourceMappingURL=clock.test.js.map
File diff suppressed because one or more lines are too long
-2
View File
@@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=rng.test.d.ts.map
-1
View File
@@ -1 +0,0 @@
{"version":3,"file":"rng.test.d.ts","sourceRoot":"","sources":["rng.test.ts"],"names":[],"mappings":""}
-317
View File
@@ -1,317 +0,0 @@
import { describe, expect, it } from 'vitest';
import {
bufferByteSize,
convertBytesLikeToArrayBuffer,
convertBytesLikeToUint8Array as toBytes,
LiteHashDRBG,
RandUtil,
} from '../src/index.js';
const range = (count) => Array.from({ length: count }, (_, idx) => idx);
const expectBytes = (actual, expected) => {
expect(Array.from(actual)).toEqual(Array.from(expected));
};
function fillBlock(body, filler = '\0', length = bufferByteSize) {
const u8Body = toBytes(body);
const u8Filler = toBytes(filler, false);
if (u8Filler.byteLength < 1) {
throw new Error('filler must have length');
}
const buffer = new Uint8Array(length);
buffer.set(u8Body, 0);
let bufferIdx = u8Body.byteLength;
while (bufferIdx + u8Filler.byteLength < length) {
buffer.set(u8Filler, bufferIdx);
bufferIdx += u8Filler.byteLength;
}
if (bufferIdx < length) {
const slice = new Uint8Array(u8Filler.buffer, u8Filler.byteOffset, length - bufferIdx);
buffer.set(slice, bufferIdx);
}
return buffer;
}
class DummyBlockRNG extends LiteHashDRBG {
repeatBlockCnt;
repeatBlock;
constructor(repeatBlock, stateIdx = 0) {
super('x');
this.repeatBlock = [];
for (const rawBlock of repeatBlock) {
const block = convertBytesLikeToArrayBuffer(rawBlock);
if (block.byteLength !== bufferByteSize) {
throw new Error('invalid block size');
}
this.repeatBlock.push(block);
}
this.repeatBlockCnt = this.repeatBlock.length;
this.stateIdx = stateIdx;
this.bufferIdx = 0;
this.genNextBlock();
}
genNextBlock() {
if (!this.repeatBlock) {
return;
}
this.buffer = this.repeatBlock[this.stateIdx];
this.bufferIdx = 0;
this.stateIdx = (this.stateIdx + 1) % this.repeatBlockCnt;
}
}
const fixedKey = 'HelloWorld';
describe('RNGtestDummy', () => {
const rng = new DummyBlockRNG([fillBlock('', '\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff')]);
it('BasicConvert', () => {
expect(toBytes('\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff', false).length).toBe(16);
});
it('SimpleByte', () => {
expectBytes(toBytes('\x00', false), rng.nextBytes(1));
expectBytes(toBytes('\x11\x22', false), rng.nextBytes(2));
expectBytes(toBytes('\x33\x44\x55', false), rng.nextBytes(3));
expectBytes(toBytes('\x66\x77\x88\x99', false), rng.nextBytes(4));
});
it('OverflowBlock', () => {
for (let idx = 0; idx < 16; idx += 1) {
expectBytes(
toBytes('\xaa\xbb\xcc\xdd\xee\xff\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99', false),
rng.nextBytes(16)
);
}
});
it('MultiBlock', () => {
expectBytes(
fillBlock('', '\xaa\xbb\xcc\xdd\xee\xff\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99', bufferByteSize * 2),
rng.nextBytes(bufferByteSize * 2)
);
});
it('bitTest', () => {
expectBytes(toBytes('\x00', false), rng.nextBits(1)); //aa
expectBytes(toBytes('\x01', false), rng.nextBits(1)); //bb
expectBytes(toBytes('\xcc', false), rng.nextBits(8)); //cc
expectBytes(toBytes('\xdd\x02', false), rng.nextBits(10)); //ddee
expectBytes(toBytes('\x7f', false), rng.nextBits(7)); //ff
expectBytes(toBytes('\x00\x11\x22\x33\x44\x55\x06', false), rng.nextBits(53));
});
it('int', () => {
expect(rng.nextInt(0xff)).toBe(0x77);
expect(rng.nextInt((1 << 16) - 1)).toBe(0x9988);
expect(rng.nextInt(0xffffffff)).toBe(0xddccbbaa);
expect(rng.nextInt()).toBe(0x0433221100ffee);
expect(rng.nextInt(0x0f)).toBe(0x05); //55
expect(rng.nextInt(0x12)).toBe(0x06); //66
expect(rng.nextInt(99)).toBe(0x08); //77(119 -> 7bit) -> 88(136 -> 8bit -> 8)
expect(rng.nextInt(0x99)).toBe(0x99); //99
expect(rng.nextInt(0xaa)).toBe(0xaa); //aa (fit Max)
});
it('float', () => {
const floatMax = 2 ** 53;
const fa = rng.nextFloat1();
expect(fa).toBe(0x1100ffeeddccbb / floatMax);
expect(0.5313720384 > fa).toBe(true);
expect(0.5313720383 < fa).toBe(true);
const fb = rng.nextFloat1();
expect(fb).toBe(0x08776655443322 / floatMax);
});
});
describe('RandUtilDummy', () => {
it('shuffle', () => {
const rng = new DummyBlockRNG([fillBlock('', '\x17\x16\x15\x14\x13\x12\x11\x10')]);
const randUtil = new RandUtil(rng);
/**
* 7, [7,1,2,3,4,5,6,0]
* 6, [7,0,2,3,4,5,6,1]
* 5, [7,0,1,3,4,5,6,2]
* 4, [7,0,1,2,4,5,6,3]
* 3, [7,0,1,2,3,5,6,4]
* 2, [7,0,1,2,3,4,6,5]
* 1, [7,0,1,2,3,4,5,6]
*/
expect(randUtil.shuffle(range(8))).toEqual([7, 0, 1, 2, 3, 4, 5, 6]);
/**
* 0, [0,1,2,3,4,5,6,7,8,9]
* 7, [0,8,2,3,4,5,6,7,1,9]
* 6, [0,8,1,3,4,5,6,7,2,9]
* 5, [0,8,1,2,4,5,6,7,3,9]
* 4, [0,8,1,2,3,5,6,7,4,9]
* 3, [0,8,1,2,3,4,6,7,5,9]
* 2, [0,8,1,2,3,4,5,7,6,9]
* 1, [0,8,1,2,3,4,5,6,7,9]
* 0, [0,8,1,2,3,4,5,6,7,9]
*/
expect(randUtil.shuffle(range(10))).toEqual([0, 8, 1, 2, 3, 4, 5, 6, 7, 9]);
});
const rng = new DummyBlockRNG([fillBlock('', '\x17\x16\x15\x14\x13\x12\x11\x10')]);
const randUtil = new RandUtil(rng);
it('choice', () => {
//0x17(7), 0x16(6)
expect(randUtil.choice([0, 1, 2, 3, 4, 5])).toBe(5);
//0x15(5), Set 순서 유지
expect(randUtil.choice(new Set([5, 3, 1, 2, 8, 0]))).toBe(8);
//0x14(4), 정렬 순서상 숫자(소-대) > 문자열(삽입순) > 심볼 순서
expect(randUtil.choice({ c: 'c', a: 'a', b: 'b', 4: 'x', 2: 't', 3: 'q' })).toBe('c');
});
it('choiceUsingWeight', () => {
//0.6275740099377194 * 38.1 = 23.91
expect(
randUtil.choiceUsingWeight({
a: 0.1,
b: 10,
tt: 2,
x: -1,
c: 20,
d: 0,
e: 6,
})
).toBe('c');
//0.658946544056166
expect(randUtil.choiceUsingWeightPair([['xx', 10]])).toBe('xx');
//0.6903152783785083 * 27.3 = 18.84560709973328
expect(
randUtil.choiceUsingWeightPair([
['e', 10],
['d', 4],
['c', 0.1],
['baba', 0.2],
['q', 9],
['xt', 4],
])
).toBe('q');
});
});
describe('RNGexpectedError', () => {
const rng = new LiteHashDRBG(fixedKey);
it('nextBits0', () => {
expect(() => rng.nextBits(0)).toThrow();
});
it('nextBits-1', () => {
expect(() => rng.nextBits(-1)).toThrow();
});
it('nextBytes0', () => {
expect(() => rng.nextBytes(0)).toThrow();
});
it('nextBytes-1', () => {
expect(() => rng.nextBytes(-1)).toThrow();
});
const randUtil = new RandUtil(rng);
it('utilEmptyChoice', () => {
expect(() => randUtil.choice([])).toThrow();
});
it('utilEmptyChoiceUsingWeight', () => {
expect(() => randUtil.choiceUsingWeight({})).toThrow();
});
it('utilEmptyChoiceUsingWeightPair', () => {
expect(() => randUtil.choiceUsingWeightPair([])).toThrow();
});
});
describe('RNGAcceptable', () => {
const rng = new LiteHashDRBG(fixedKey);
it('RNG', () => {
rng.nextInt(0);
rng.nextInt(2 ** 53 - 1);
rng.nextBytes(65);
rng.nextBits(512);
});
const randUtil = new RandUtil(rng);
it('RandUtil', () => {
randUtil.choice([0, 0, 0]);
randUtil.choiceUsingWeight({
0: 0,
1: -1,
});
randUtil.choiceUsingWeightPair([
[0, 0],
[1, 0],
[2, -2],
]);
randUtil.nextBool(1.1);
randUtil.nextBool(-0.1);
randUtil.shuffle([]);
randUtil.shuffle([1]);
randUtil.nextRange(0, 0);
randUtil.nextRangeInt(0, 0);
randUtil.nextRange(1, -1);
randUtil.nextRangeInt(1, -1);
});
it('RNGLong', () => {
const longKey = fixedKey;
for (let idx = 0; idx < 8; idx += 1) {
longKey.concat(longKey);
}
const rngLong = new LiteHashDRBG(longKey);
for (let idx = 0; idx < 10; idx += 1) {
rngLong.nextBytes(16);
}
});
});
/* Python TestVector
import hashlib
import struct
fixedKey = 'HelloWorld'.encode('utf-8')
def hash(key, idx):
idxV = struct.pack("<I", idx)
return hashlib.sha512(key + idxV).digest()
for idx in range(5):
print(hash(fixedKey, idx).hex())
*/
describe('RNG', () => {
//JS - PHP 일치 확인 정도로.
const testVector = Buffer.from(
[
'24d9ccd648556255fd0ee9f5b29918de90617341958b3b354d572167e4dee02b757816a2bbe0b502c52413ffd384381a9d7b4e193df6f4345d6a95e111d661c4',
'2e9264512f6f4b080cf1376b74fab6878ecf4a6e185942d2e5b22cf923885b9952d40601a414225d6901417fd4ce9368ac77e4a63d3fc9b58ab952bb8c33f165',
'8e2ebf5af6283a1b18f4c044c86c20d02be3890613c4cc8b7c6b7b35581263b972a82630df69a9289988422d7c3a9be5edf78d5de16fabd01e5dd4e458068d8a',
'398596047ba547bfe371ec863a3e019ab0dbc4bb3b27e9077685aae4283ff6bbccfd981d92f9358f7efffbb72a940414802d98466d132e2ad0a16a12946d5f47',
'b3606fe9b18c4aa7315e78bb9e47cb51cc4e203fcc2e631f0405c1b872c8e1cb5b6415ea74bbb77fffaaadb002b47cb4f4628dc0709634365b187667f5c708cb',
].join(''),
'hex'
);
it('bytes', () => {
const rng = new LiteHashDRBG(fixedKey);
let offset = 0;
expectBytes(rng.nextBytes(10), testVector.slice(offset, offset + 10));
offset += 10;
expectBytes(rng.nextBytes(32), testVector.slice(offset, offset + 32));
offset += 32;
expectBytes(rng.nextBytes(1), testVector.slice(offset, offset + 1));
offset += 1;
expectBytes(rng.nextBytes(64), testVector.slice(offset, offset + 64));
offset += 64;
expectBytes(rng.nextBytes(5), testVector.slice(offset, offset + 5));
offset += 5;
const lastA = rng.nextBytes(16, 18);
const lastB = new Uint8Array(18);
lastB.set(testVector.slice(offset, offset + 16));
expectBytes(lastA, lastB);
});
it('bits', () => {
const rng = new LiteHashDRBG(fixedKey);
let offset = 0;
const testBits = [10, 4, 15, 32, 7, 99, 512, 1, 2, 3];
for (const bits of testBits) {
const bytes = Math.ceil(bits / 8);
const A = rng.nextBits(bits);
const B = new Uint8Array(testVector.slice(offset, offset + bytes));
offset += bytes;
if (bits % 8 !== 0) {
const bitMask = 0xff >> (8 - (bits % 8));
B[bytes - 1] &= bitMask;
}
expectBytes(A, B);
}
});
it('float', () => {
const rng = new LiteHashDRBG(fixedKey);
const rng2 = new DummyBlockRNG([
new Uint8Array(testVector.slice(bufferByteSize * 0, bufferByteSize * 1)),
new Uint8Array(testVector.slice(bufferByteSize * 1, bufferByteSize * 2)),
new Uint8Array(testVector.slice(bufferByteSize * 2, bufferByteSize * 3)),
new Uint8Array(testVector.slice(bufferByteSize * 3, bufferByteSize * 4)),
new Uint8Array(testVector.slice(bufferByteSize * 4, bufferByteSize * 5)),
]);
for (let i = 0; i < 18; i++) {
expect(rng.nextFloat1()).toBe(rng2.nextFloat1());
}
});
});
//# sourceMappingURL=rng.test.js.map
File diff suppressed because one or more lines are too long
+39 -33
View File
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
bufferByteSize,
ConstantRNG,
convertBytesLikeToArrayBuffer,
convertBytesLikeToUint8Array as toBytes,
LiteHashDRBG,
@@ -238,46 +239,51 @@ describe('RNGexpectedError', () => {
});
});
describe('RNGAcceptable', () => {
const rng = new LiteHashDRBG(fixedKey);
it('RNG', () => {
rng.nextInt(0);
rng.nextInt(2 ** 53 - 1);
rng.nextBytes(65);
rng.nextBits(512);
describe('RNG boundary behavior', () => {
it('returns values at supported zero/max/large-buffer boundaries', () => {
const rng = new LiteHashDRBG(fixedKey);
expect(rng.nextInt(0)).toBe(0);
expect(rng.nextInt(2 ** 53 - 1)).toBe(656_721_283_176_740);
expect(rng.nextBytes(65)).toHaveLength(65);
expect(rng.nextBits(512)).toHaveLength(64);
});
const randUtil = new RandUtil(rng);
it('RandUtil', () => {
randUtil.choice([0, 0, 0]);
randUtil.choiceUsingWeight({
0: 0,
1: -1,
});
randUtil.choiceUsingWeightPair([
[0, 0],
[1, 0],
[2, -2],
]);
randUtil.nextBool(1.1);
randUtil.nextBool(-0.1);
randUtil.shuffle([]);
randUtil.shuffle([1]);
randUtil.nextRange(0, 0);
randUtil.nextRangeInt(0, 0);
randUtil.nextRange(1, -1);
randUtil.nextRangeInt(1, -1);
it('defines deterministic behavior for degenerate utility inputs', () => {
const minRand = new RandUtil(new ConstantRNG(0));
const maxRand = new RandUtil(new ConstantRNG(1));
expect(minRand.choice([0, 0, 0])).toBe(0);
expect(minRand.choiceUsingWeight({ 0: 0, 1: -1 })).toBe('0');
expect(
minRand.choiceUsingWeightPair([
[0, 0],
[1, 0],
[2, -2],
])
).toBe(0);
expect(minRand.nextBool(1.1)).toBe(true);
expect(minRand.nextBool(-0.1)).toBe(false);
expect(minRand.shuffle([])).toEqual([]);
expect(minRand.shuffle([1])).toEqual([1]);
expect(minRand.nextRange(0, 0)).toBe(0);
expect(minRand.nextRangeInt(0, 0)).toBe(0);
expect(minRand.nextRange(1, -1)).toBe(1);
expect(minRand.nextRangeInt(1, -1)).toBe(1);
expect(maxRand.nextRange(1, -1)).toBe(-1);
expect(maxRand.nextRangeInt(1, -1)).toBe(-1);
});
it('RNGLong', () => {
const longKey = fixedKey;
it('hashes the complete expanded long seed', () => {
let longKey = fixedKey;
for (let idx = 0; idx < 8; idx += 1) {
longKey.concat(longKey);
longKey += longKey;
}
const rngLong = new LiteHashDRBG(longKey);
for (let idx = 0; idx < 10; idx += 1) {
rngLong.nextBytes(16);
}
expect(Buffer.from(rngLong.nextBytes(32)).toString('hex')).toBe(
'7e44b8180c0d254759a70aee891a5f6ba45c8016e02cb8ee51f0b22e600a4dd1'
);
});
});
-2
View File
@@ -1,2 +0,0 @@
export {};
//# sourceMappingURL=test-rngs.test.d.ts.map
@@ -1 +0,0 @@
{"version":3,"file":"test-rngs.test.d.ts","sourceRoot":"","sources":["test-rngs.test.ts"],"names":[],"mappings":""}
-65
View File
@@ -1,65 +0,0 @@
import { describe, expect, it } from 'vitest';
import { ConstantRNG, MidpointRNG, SequenceRNG, SineRNG } from '../src/index.js';
const toArray = (bytes) => Array.from(bytes);
describe('TestRNG:Constant', () => {
it('returns fixed 0', () => {
const rng = new ConstantRNG(0);
expect(rng.nextFloat1()).toBe(0);
expect(rng.nextInt(10)).toBe(0);
expect(toArray(rng.nextBytes(3))).toEqual([0, 0, 0]);
expect(toArray(rng.nextBits(3))).toEqual([0]);
});
it('returns fixed 1', () => {
const rng = new ConstantRNG(1);
expect(rng.nextFloat1()).toBe(1);
expect(rng.nextInt(10)).toBe(10);
expect(toArray(rng.nextBytes(2))).toEqual([255, 255]);
expect(toArray(rng.nextBits(3))).toEqual([7]);
});
});
describe('TestRNG:Midpoint', () => {
it('returns midpoint for int/float', () => {
const rng = new MidpointRNG();
expect(rng.nextFloat1()).toBe(0.5);
expect(rng.nextInt(9)).toBe(4);
expect(rng.nextInt(10)).toBe(5);
});
it('alternates bits', () => {
const rng = new MidpointRNG();
expect(toArray(rng.nextBits(4))).toEqual([10]);
expect(toArray(rng.nextBits(4))).toEqual([10]);
});
});
describe('TestRNG:Sine', () => {
it('follows sine wave with period/amplitude', () => {
const rng = new SineRNG(4, 0.5, 0);
expect(rng.nextFloat1()).toBeCloseTo(0.5, 8);
expect(rng.nextFloat1()).toBeCloseTo(1, 8);
expect(rng.nextFloat1()).toBeCloseTo(0.5, 8);
expect(rng.nextFloat1()).toBeCloseTo(0, 8);
});
it('maps float to int range', () => {
const rng = new SineRNG(4, 0.5, 0);
expect(rng.nextInt(9)).toBe(5);
expect(rng.nextInt(9)).toBe(9);
});
});
describe('TestRNG:Sequence', () => {
it('cycles fixed sequence', () => {
const rng = new SequenceRNG([0, 0.25, 0.5, 0.75, 1]);
expect(rng.nextFloat1()).toBe(0);
expect(rng.nextFloat1()).toBe(0.25);
expect(rng.nextFloat1()).toBe(0.5);
expect(rng.nextFloat1()).toBe(0.75);
expect(rng.nextFloat1()).toBe(1);
expect(rng.nextFloat1()).toBe(0);
});
it('converts sequence to bytes and ints', () => {
const rng = new SequenceRNG([0, 0.5, 1]);
expect(toArray(rng.nextBytes(3))).toEqual([0, 128, 255]);
expect(rng.nextInt(8)).toBe(0);
expect(rng.nextInt(8)).toBe(4);
expect(rng.nextInt(8)).toBe(8);
});
});
//# sourceMappingURL=test-rngs.test.js.map
File diff suppressed because one or more lines are too long
@@ -225,7 +225,7 @@ describe('Nation Actions', () => {
});
describe('che_필사즉생 (Last Stand)', () => {
it('increases experience and sets strategic limit', () => {
it('applies the legacy three-turn gains and global delay', () => {
const nation = buildNation(1);
const general = buildGeneral(1, 1, 1);
const definition = new LastStandAction([]);
@@ -240,8 +240,11 @@ describe('Nation Actions', () => {
definition.resolve(context as any, {});
expect(general.experience).toBeGreaterThan(100);
expect(nation.meta.strategic_cmd_limit).toBeGreaterThan(0);
expect(general.experience).toBe(115);
expect(general.dedication).toBe(115);
expect(general.train).toBe(100);
expect(general.atmos).toBe(100);
expect(nation.meta.strategic_cmd_limit).toBe(9);
});
});
+2 -2
View File
@@ -9,7 +9,7 @@ import { parseScenarioDefaults, parseScenarioDefinition } from '../src/scenario/
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..', '..');
const scenarioRoot = path.join(repoRoot, 'legacy', 'hwe', 'scenario');
const scenarioRoot = path.join(repoRoot, 'resources', 'scenario');
const readJson = async (filePath: string): Promise<unknown> => {
const raw = await fs.readFile(filePath, 'utf8');
@@ -17,7 +17,7 @@ const readJson = async (filePath: string): Promise<unknown> => {
};
describe('scenario parser', () => {
it('reads defaults from legacy default.json', async () => {
it('reads defaults from the tracked legacy-format default.json', async () => {
const defaultsRaw = await readJson(path.join(scenarioRoot, 'default.json'));
const defaults = parseScenarioDefaults(defaultsRaw);
+112 -60
View File
@@ -7,10 +7,11 @@ import { commandSpec as declareWarSpec } from '../../src/actions/turn/nation/che
import { commandSpec as deploySpec } from '../../src/actions/turn/general/che_출병.js';
import type { TurnCommandEnv } from '../../src/actions/turn/commandEnv.js';
import { processDiplomacyMonth, DIPLOMACY_STATE, type DiplomacyEntry } from '../../src/diplomacy/index.js';
import { buildWarConfig, buildWarAftermathConfig } from '../../src/actions/turn/actionContextHelpers.js';
import { evaluateConstraints } from '../../src/constraints/evaluate.js';
import type { ConstraintContext, RequirementKey, StateView } from '../../src/constraints/types.js';
describe('Diplomacy Scenario', () => {
it('should handle War Declaration and prevent/allow deployment accordingly', async () => {
it('changes deployment from denied to allowed when a declaration becomes war', async () => {
// 1. Setup World
const NATION_A_ID = 1;
const NATION_B_ID = 2; // Target nation
@@ -134,8 +135,49 @@ describe('Diplomacy Scenario', () => {
unitSet: {
id: 'default',
name: 'default',
crewTypes: [{ id: 1, name: 'Infantry', armType: 1, cost: 10, requirements: [] }],
} as any,
defaultCrewTypeId: 1,
armTypes: { 0: '성벽', 1: '보병' },
crewTypes: [
{
id: 0,
name: '성벽',
armType: 0,
attack: 0,
defence: 100,
speed: 1,
avoid: 0,
magicCoef: 0,
cost: 0,
rice: 0,
requirements: [],
attackCoef: {},
defenceCoef: {},
info: [],
initSkillTrigger: null,
phaseSkillTrigger: null,
iActionList: null,
},
{
id: 1,
name: '보병',
armType: 1,
attack: 100,
defence: 100,
speed: 5,
avoid: 0,
magicCoef: 0,
cost: 10,
rice: 1,
requirements: [],
attackCoef: {},
defenceCoef: {},
info: [],
initSkillTrigger: null,
phaseSkillTrigger: null,
iActionList: null,
},
],
},
nations: [mockNationA, mockNationB],
cities: [mockCityA, mockCityB],
generals: [mockGeneralA],
@@ -191,55 +233,71 @@ describe('Diplomacy Scenario', () => {
expect(diplomacyAB).toBeDefined();
expect(diplomacyAB?.state).toBe(DIPLOMACY_STATE.DECLARATION);
// Pre-calculate context data needed for Dispatch
const warConfig = buildWarConfig(snapshot.scenarioConfig, snapshot.unitSet!);
const aftermathConfig = buildWarAftermathConfig(snapshot.scenarioConfig, warConfig.castleCrewTypeId);
const warTime = {
year: 200,
month: 1,
season: 0,
turn: 1,
};
const seedBase = 'test_seed';
const buildDispatchContext = (destCityId: number) => {
const destCity = world.getCity(destCityId)!;
const destNation = world.getNation(destCity.nationId);
warTime.year = runner.currentDate.getFullYear();
warTime.month = runner.currentDate.getMonth() + 1;
warTime.season = Math.floor(runner.currentDate.getMonth() / 3);
const dispatchArgs = { destCityId: 2 };
const buildConstraintView = (): StateView => {
const get = (requirement: RequirementKey): unknown | null => {
switch (requirement.kind) {
case 'general':
case 'destGeneral':
return world.getGeneral(requirement.id) ?? null;
case 'generalList':
return world.getAllGenerals();
case 'city':
case 'destCity':
return world.getCity(requirement.id) ?? null;
case 'nation':
case 'destNation':
return world.getNation(requirement.id) ?? null;
case 'nationList':
return world.getAllNations();
case 'diplomacy':
return world.getDiplomacy(requirement.srcNationId, requirement.destNationId) ?? null;
case 'diplomacyList':
return world.snapshot.diplomacy;
case 'arg':
return dispatchArgs[requirement.key as keyof typeof dispatchArgs] ?? null;
case 'env':
if (requirement.key === 'map') return world.snapshot.map;
if (requirement.key === 'cities') return world.getAllCities();
if (requirement.key === 'nations') return world.getAllNations();
if (requirement.key === 'relYear') return 200;
if (requirement.key === 'openingPartYear') return 200;
return null;
}
};
return {
destCity,
destNation,
warConfig,
aftermathConfig,
time: { ...warTime },
seedBase,
map: world.snapshot.map,
unitSet: world.snapshot.unitSet,
cities: world.getAllCities(),
nations: world.getAllNations(),
generals: world.getAllGenerals(),
diplomacy: world.snapshot.diplomacy,
has: (requirement) => get(requirement) !== null,
get,
};
};
// 3. Try to Deploy
const deployDef = deploySpec.createDefinition(systemEnv);
await runner.runTurn([
{
generalId: 1,
commandKey: 'che_출병',
resolver: deployDef,
args: { destCityId: 2 },
context: buildDispatchContext(2),
const buildDispatchConstraintContext = (): ConstraintContext => ({
actorId: mockGeneralA.id,
cityId: mockGeneralA.cityId,
nationId: mockGeneralA.nationId,
destCityId: dispatchArgs.destCityId,
destNationId: NATION_B_ID,
args: dispatchArgs,
env: {
relYear: 200,
openingPartYear: 200,
},
]);
mode: 'full',
});
expect(world.snapshot.troops.length).toBe(0);
// 3. A declaration is not yet a war, so deployment must be rejected.
const deployDef = deploySpec.createDefinition(systemEnv);
const declarationResult = evaluateConstraints(
deployDef.buildConstraints(buildDispatchConstraintContext(), dispatchArgs),
buildDispatchConstraintContext(),
buildConstraintView()
);
expect(declarationResult).toMatchObject({
kind: 'deny',
constraintName: 'hasRouteWithEnemy',
reason: '교전중인 국가가 아닙니다.',
});
expect(world.getGeneral(1)?.experience).toBe(100);
// 4. Simulate State Transition
for (let i = 0; i < 24; i++) {
@@ -267,18 +325,12 @@ describe('Diplomacy Scenario', () => {
const diplomacyAB_After = world.getDiplomacy(NATION_A_ID, NATION_B_ID);
expect(diplomacyAB_After?.state).toBe(DIPLOMACY_STATE.WAR);
// 5. Try to Deploy (Should Succeed)
await runner.runTurn([
{
generalId: 1,
commandKey: 'che_출병',
resolver: deployDef,
args: { destCityId: 2 },
context: buildDispatchContext(2),
},
]);
const generalAfter = world.getGeneral(1)!;
console.log(`General Exp: ${mockGeneralA.experience} -> ${generalAfter.experience}`);
// 5. The same command becomes valid after the declaration reaches WAR.
const warResult = evaluateConstraints(
deployDef.buildConstraints(buildDispatchConstraintContext(), dispatchArgs),
buildDispatchConstraintContext(),
buildConstraintView()
);
expect(warResult).toEqual({ kind: 'allow' });
});
});
@@ -141,8 +141,7 @@ describe('Domestic Affairs Scenario', () => {
// 4. Verify
const updatedCity = world.getCity(1)!;
console.log(`Agriculture: 500 -> ${updatedCity.agriculture}`);
expect(updatedCity.agriculture).toBeGreaterThan(500);
expect(updatedCity.agriculture).toBe(600);
});
it('should not increase agriculture when city is already maxed', async () => {
@@ -224,10 +224,18 @@ describe('che_NPC능동', () => {
).rejects.toThrow('NPC가 아닙니다.');
});
it('should fail if args are invalid', async () => {
// Arg validation happens in parseArgs or resolver check.
// Simulating invalid args via direct usage of resolver might bypass parseArgs if using `resolver` object directly with raw args?
// No, verify it returns null or throws.
// Here we just skip for brevity or setup minimal test.
it('rejects structurally invalid command arguments', async () => {
const definition = (
await import('../../../src/actions/turn/general/che_NPC능동.js')
).commandSpec.createDefinition({} as TurnCommandEnv);
expect(definition.parseArgs(null)).toBeNull();
expect(definition.parseArgs({ optionText: '순간이동' })).toBeNull();
expect(definition.parseArgs({ optionText: '순간이동', destCityId: '101' })).toBeNull();
expect(definition.parseArgs({ optionText: '알수없음', destCityId: 101 })).toBeNull();
expect(definition.parseArgs({ optionText: '순간이동', destCityId: 101 })).toEqual({
optionText: '순간이동',
destCityId: 101,
});
});
});
+2 -5
View File
@@ -144,7 +144,6 @@ describe('Troop Management Scenario', () => {
]);
const generalAfterDraft = world.getGeneral(1)!;
console.log(`Drafted: ${generalAfterDraft.crew}`);
expect(generalAfterDraft.crew).toBe(1000);
// 3. Train
@@ -159,8 +158,7 @@ describe('Troop Management Scenario', () => {
]);
const generalAfterTrain = world.getGeneral(1)!;
console.log(`Train: 10 -> ${generalAfterTrain.train}`);
expect(generalAfterTrain.train).toBeGreaterThan(10);
expect(generalAfterTrain.train).toBe(75);
// 4. Boost Morale
const atmosDef = atmosSpec.createDefinition(systemEnv);
@@ -174,7 +172,6 @@ describe('Troop Management Scenario', () => {
]);
const generalAfterAtmos = world.getGeneral(1)!;
console.log(`Atmos: 10 -> ${generalAfterAtmos.atmos}`);
expect(generalAfterAtmos.atmos).toBeGreaterThan(10);
expect(generalAfterAtmos.atmos).toBe(75);
});
});
+20 -13
View File
@@ -1,4 +1,5 @@
import { enablePatches } from 'immer';
import { LiteHashDRBG, RandUtil } from '@sammo-ts/common';
import type { City, General, Nation, GeneralId, NationId, CityId } from '../src/domain/entities.js';
import type { WorldSnapshot } from '../src/world/types.js';
import {
@@ -176,10 +177,12 @@ export interface TestCommand {
export class TestGameRunner {
world: InMemoryWorld;
currentDate: Date;
private readonly seedBase: string;
constructor(world: InMemoryWorld, startYear: number, startMonth: number) {
constructor(world: InMemoryWorld, startYear: number, startMonth: number, seedBase = 'test-game-runner') {
this.world = world;
this.currentDate = new Date(startYear, startMonth - 1);
this.seedBase = seedBase;
}
nextGeneralId = 1;
@@ -190,29 +193,33 @@ export class TestGameRunner {
entries: [{ startMinute: 0, tickMinutes: 60 }],
};
for (const cmd of commands) {
for (const [commandIndex, cmd] of commands.entries()) {
const general = this.world.getGeneral(cmd.generalId);
if (!general) continue;
if (!general) {
throw new Error(`General ${cmd.generalId} does not exist`);
}
const city = this.world.getCity(general.cityId);
if (!city) throw new Error(`General ${general.id} is in non-existent city ${general.cityId}`);
const nation = general.nationId ? this.world.getNation(general.nationId) : null;
const rng = new RandUtil(
LiteHashDRBG.build(
[
this.seedBase,
this.currentDate.toISOString(),
String(commandIndex),
String(general.id),
cmd.commandKey,
].join('|')
)
);
const inputContext = {
general,
city,
nation: nation || null,
rng: {
real: () => Math.random(),
int: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min,
nextInt: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min,
next: () => Math.random(),
nextBool: () => Math.random() < 0.5,
nextRange: (min: number, max: number) => Math.random() * (max - min) + min,
nextRangeInt: (min: number, max: number) => Math.floor(Math.random() * (max - min)) + min,
nextFloat1: () => Math.random(),
} as any,
rng,
year: this.currentDate.getFullYear(),
month: this.currentDate.getMonth() + 1,