silphius/app/ecs/query.test.js

93 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-06-10 22:42:30 -05:00
import {expect, test} from 'vitest';
2024-06-14 15:18:55 -05:00
import Arbitrary from './arbitrary.js';
2024-06-10 22:42:30 -05:00
import Query from './query.js';
2024-06-14 15:18:55 -05:00
import Schema from './schema.js';
2024-06-10 22:42:30 -05:00
2024-06-14 15:18:55 -05:00
function wrapSpecification(name, specification) {
return class Component extends Arbitrary {
static name = name;
static schema = new Schema({
type: 'object',
properties: specification,
});
};
}
const A = new (wrapSpecification('A', {a: {type: 'int32', defaultValue: 420}}));
const B = new (wrapSpecification('B', {b: {type: 'int32', defaultValue: 69}}));
const C = new (wrapSpecification('C', {c: {type: 'int32'}}));
2024-06-10 22:42:30 -05:00
2024-06-15 19:38:49 -05:00
const Components = {A, B, C};
Components.A.createMany([[2], [3]]);
Components.B.createMany([[1], [2]]);
Components.C.createMany([[2], [4]]);
2024-06-10 22:42:30 -05:00
2024-06-26 07:41:07 -05:00
const fakeEcs = (Components) => ({
Components,
get(id) {
return Object.fromEntries(
Object.entries(Components)
.map(([componentName, Component]) => [componentName, Component.get(id)])
.concat([['id', id]])
);
},
});
2024-06-10 22:42:30 -05:00
function testQuery(parameters, expected) {
2024-06-26 07:41:07 -05:00
const query = new Query(parameters, fakeEcs(Components));
2024-06-10 22:42:30 -05:00
query.reindex([1, 2, 3]);
expect(query.count)
.to.equal(expected.length);
for (const _ of query.select()) {
2024-06-26 07:41:07 -05:00
expect(expected.includes(_.id))
2024-06-10 22:42:30 -05:00
.to.equal(true);
}
}
test('can query all', () => {
testQuery([], [1, 2, 3]);
});
test('can query some', () => {
testQuery(['A'], [2, 3]);
testQuery(['A', 'B'], [2]);
});
test('can query excluding', () => {
testQuery(['!A'], [1]);
testQuery(['A', '!B'], [3]);
});
test('can deindex', () => {
2024-06-26 07:41:07 -05:00
const query = new Query(['A'], fakeEcs(Components));
2024-06-10 22:42:30 -05:00
query.reindex([1, 2, 3]);
expect(query.count)
.to.equal(2);
query.deindex([2]);
expect(query.count)
.to.equal(1);
});
test('can reindex', () => {
2024-06-14 15:18:55 -05:00
const Test = new (wrapSpecification('Test', {a: {type: 'int32', defaultValue: 420}}));
2024-06-10 22:42:30 -05:00
Test.createMany([[2], [3]]);
2024-06-26 07:41:07 -05:00
const query = new Query(['Test'], fakeEcs({Test}));
2024-06-10 22:42:30 -05:00
query.reindex([2, 3]);
expect(query.count)
.to.equal(2);
Test.destroy(2);
query.reindex([2, 3]);
expect(query.count)
.to.equal(1);
});
test('can select', () => {
2024-06-26 07:41:07 -05:00
const query = new Query(['A'], fakeEcs(Components));
2024-06-10 22:42:30 -05:00
query.reindex([1, 2, 3]);
const it = query.select();
2024-06-26 07:41:07 -05:00
const {value: {A}} = it.next();
expect(A.a)
2024-06-10 22:42:30 -05:00
.to.equal(420);
});