96 lines
2.7 KiB
TypeScript
96 lines
2.7 KiB
TypeScript
import { expect, test } from 'bun:test';
|
|
import {
|
|
frozenStateCopy,
|
|
stateCopy,
|
|
} from '../../apps/stock/orchestrator/src/strategies/strategy-decision';
|
|
|
|
test('copying preserves canonical key order and detaches each alias while freezing only copies', () => {
|
|
const shared = { z: [2, 3], a: 1 };
|
|
const input = { z: shared, a: shared, ...JSON.parse('{"__proto__":{"x":1}}') };
|
|
const copy = frozenStateCopy(input) as typeof input;
|
|
expect(JSON.stringify(copy)).toBe(
|
|
'{"__proto__":{"x":1},"a":{"a":1,"z":[2,3]},"z":{"a":1,"z":[2,3]}}'
|
|
);
|
|
expect(Object.getPrototypeOf(copy)).toBe(Object.prototype);
|
|
expect(copy.a).not.toBe(copy.z);
|
|
expect(copy.a.z).not.toBe(shared.z);
|
|
expect(Object.isFrozen(copy)).toBe(true);
|
|
expect(Object.isFrozen(copy.a)).toBe(true);
|
|
expect(Object.isFrozen(copy.a.z)).toBe(true);
|
|
expect(Object.isFrozen(shared)).toBe(false);
|
|
shared.z.push(4);
|
|
expect(copy.a.z).toEqual([2, 3]);
|
|
const mutable = stateCopy(copy) as typeof input;
|
|
expect(Object.isFrozen(mutable.a.z)).toBe(false);
|
|
mutable.a.z.push(9);
|
|
expect(copy.a.z).toEqual([2, 3]);
|
|
});
|
|
|
|
test('both copying paths reject lossy state without reading getters, even when frozen', () => {
|
|
let reads = 0;
|
|
const accessor = Object.defineProperty({}, 'x', {
|
|
enumerable: true,
|
|
get() {
|
|
reads++;
|
|
return 1;
|
|
},
|
|
});
|
|
const arrayAccessor = Object.defineProperty([1], '0', {
|
|
enumerable: true,
|
|
get() {
|
|
reads++;
|
|
return 1;
|
|
},
|
|
});
|
|
const cyclic: { self?: unknown } = {};
|
|
cyclic.self = cyclic;
|
|
const extraArrayKey = Object.assign([1], { extra: 2 });
|
|
const hiddenIndex = Object.defineProperty([1], '0', { enumerable: false });
|
|
const invalid = [
|
|
undefined,
|
|
-0,
|
|
NaN,
|
|
Infinity,
|
|
-Infinity,
|
|
1n,
|
|
() => 0,
|
|
Symbol('x'),
|
|
new Date(),
|
|
Object.create(null),
|
|
Object.create({ x: 1 }),
|
|
[, 1],
|
|
[undefined],
|
|
extraArrayKey,
|
|
hiddenIndex,
|
|
{ [Symbol('x')]: 1 },
|
|
Object.defineProperty({}, 'hidden', { value: 1 }),
|
|
accessor,
|
|
arrayAccessor,
|
|
cyclic,
|
|
];
|
|
for (const copy of [stateCopy, frozenStateCopy]) {
|
|
for (const value of invalid) expect(() => copy(value)).toThrow();
|
|
for (const value of [accessor, arrayAccessor, cyclic])
|
|
expect(() => copy(Object.freeze(value))).toThrow();
|
|
}
|
|
expect(reads).toBe(0);
|
|
});
|
|
|
|
test('both copying paths agree on empty containers, primitive roots and nonwritable data', () => {
|
|
for (const value of [
|
|
null,
|
|
true,
|
|
false,
|
|
'',
|
|
'x',
|
|
0,
|
|
1.25,
|
|
[],
|
|
{},
|
|
Object.freeze([1, { a: 'x' }]),
|
|
Object.defineProperty({}, 'x', { value: 1, enumerable: true }),
|
|
]) {
|
|
expect(frozenStateCopy(value)).toEqual(stateCopy(value));
|
|
expect(JSON.stringify(frozenStateCopy(value))).toBe(JSON.stringify(stateCopy(value)));
|
|
}
|
|
});
|