silphius/app/ecs/query.test.js
2024-06-26 21:36:45 -05:00

89 lines
2.2 KiB
JavaScript

import {expect, test} from 'vitest';
import Component from './component.js';
import Query from './query.js';
function wrapProperties(name, properties) {
return class WrappedComponent extends Component {
static name = name;
static properties = properties;
};
}
const A = new (wrapProperties('A', {a: {type: 'int32', defaultValue: 420}}));
const B = new (wrapProperties('B', {b: {type: 'int32', defaultValue: 69}}));
const C = new (wrapProperties('C', {c: {type: 'int32'}}));
const Components = {A, B, C};
Components.A.createMany([[2], [3]]);
Components.B.createMany([[1], [2]]);
Components.C.createMany([[2], [4]]);
const fakeEcs = (Components) => ({
Components,
get(id) {
return Object.fromEntries(
Object.entries(Components)
.map(([componentName, Component]) => [componentName, Component.get(id)])
.concat([['id', id]])
);
},
});
function testQuery(parameters, expected) {
const query = new Query(parameters, fakeEcs(Components));
query.reindex([1, 2, 3]);
expect(query.count)
.to.equal(expected.length);
for (const _ of query.select()) {
expect(expected.includes(_.id))
.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', () => {
const query = new Query(['A'], fakeEcs(Components));
query.reindex([1, 2, 3]);
expect(query.count)
.to.equal(2);
query.deindex([2]);
expect(query.count)
.to.equal(1);
});
test('can reindex', () => {
const Test = new (wrapProperties('Test', {a: {type: 'int32', defaultValue: 420}}));
Test.createMany([[2], [3]]);
const query = new Query(['Test'], fakeEcs({Test}));
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', () => {
const query = new Query(['A'], fakeEcs(Components));
query.reindex([1, 2, 3]);
const it = query.select();
const {value: {A}} = it.next();
expect(A.a)
.to.equal(420);
});