graph-ecs/tests/query.test.js

91 lines
2.9 KiB
JavaScript

import { before, describe, it } from 'node:test'
import { addComponent, addEntity, createWorld, defineComponent, Types } from 'bitecs'
import assert from './assert.js'
import { query } from '../src/query.js'
import { identity } from '../src/fn.js'
let engine = {}
const create = (world, ...components) => {
const entity = addEntity(world)
components.forEach(cmp => addComponent(world, cmp, entity))
return entity
}
const relate = (world, a, type, ...b) => {
return b.map(v => {
const edge = addEntity(world)
addComponent(world, type, edge)
type.from[edge] = a
type.to[edge] = v
return edge
})
}
describe('query', () => {
before(() => {
const world = { default: createWorld() }
const component = {
Entity: identity,
Player: defineComponent(null, 10),
NPC: defineComponent(null, 10),
Health: defineComponent({ current: Types.ui8, max: Types.ui8 }),
Knows: defineComponent({
from: Types.eid,
to: Types.eid
}, 10)
}
engine = { world, component }
})
it('should execute basic queries', () => {
const world = engine.world.default
const { Player, NPC, Knows } = engine.component
const player = create(world, Player) // 0
const a = create(world, NPC) // 1
const b = create(world, NPC) // 2
const c = create(world, NPC) // 3
relate(world, player, Knows, a, c) // 4, 5
relate(world, a, Knows, player, b, c) // 6, 7, 8
relate(world, b, Knows, a) // 9
relate(world, c, Knows, player) // 10
//assert.deepEqual(
// query('MATCH (player:Player) RETURN player', engine).unwrap(),
// [{ player: {} }]
//)
//assert.deepEqual(
// query('MATCH (player:Player)-[e1:Knows]->(a:NPC) RETURN player, e1, a', engine).unwrap(),
// [
// { player: {}, e1: { from: 0, to: 1 }, a: {} },
// { player: {}, e1: { from: 0, to: 3 }, a: {} }
// ]
//)
assert.deepEqual(
query('MATCH (player:Player)-[e1:Knows]->(a:NPC)-[e2:Knows]->(b:NPC) RETURN player, e1, a, e2, b', engine).unwrap(),
[
{ player: {}, e1: { from: 0, to: 1 }, a: {}, e2: { from: 1, to: 2 }, b: {} },
{ player: {}, e1: { from: 0, to: 1 }, a: {}, e2: { from: 1, to: 3 }, b: {} }
]
)
})
//it('should match multiple components', () => {
// const world = engine.world.default
// const { Player, Health } = engine.component
// const player = create(world, Player, Health)
// Health.max[player] = 50
// Health.current[player] = 25
// assert.deepEqual(
// query('MATCH (e:Entity, h:Health) return e, h.max', engine).unwrap(),
// [{ e: 11, h: { current: 25, max: 50 } }]
// )
//})
})