brainy/tests/unit/brainy-core.unit.test.ts
David Snelling 478fa176f2 refactor(8.0): delete DataAPI — superseded by Db persist/restore + import API + stats
The legacy backup/import/export/stats facade (src/api/DataAPI.ts) drifted
from the modern entity shape and every job it did now has a first-class
surface. Delete it and brain.data(), and rewire the CLI:

- data-stats → brain.stats() (full BrainyStats report: per-type breakdowns,
  indexed fields, index health, storage backend, writer lock, version)
- clean → brain.clear()
- export → alias of snapshot; a db.persist() snapshot is the full-fidelity
  export format (open with Brainy.load, load wholesale with brainy restore);
  external data ingestion remains brainy import (UniversalImportAPI)

Rewiring clean onto brain.clear() exposed two real bugs, both fixed:

- clear() left this.graphIndex undefined forever — any graph-touching call
  afterwards (relate, getNeighbors, stats) crashed. clear() now re-resolves
  the graph index exactly as init() does and re-wires the shared UUID↔int
  resolver, and re-resolves the metadata index with the same provider
  fallback as init().
- storage.clear() reset the legacy totals but not the per-type/subtype
  count rollups or id→type caches, so stats() reported phantom counts for
  deleted entities. Both adapters now delegate derived-state reset to
  reloadDerivedState(), the same path restore-from-snapshot uses.

One-shot CLI commands (data-stats, clean, snapshot/export, restore,
history, generation) now close the brain and exit explicitly — global
cache timers otherwise keep the process alive holding the writer lock.

Verified: build clean, 1383/1383 unit tests, 24/24 db-mvcc integration,
plus an end-to-end CLI smoke (add → data-stats → export → clean →
data-stats).
2026-06-11 09:05:12 -07:00

270 lines
No EOL
8.1 KiB
TypeScript

/**
* Unit Tests for Brainy 3.0 Core Functionality
*
* Tests business logic with real embeddings - production ready
* No mocks, no fakes, real implementation
*/
import { describe, it, expect, beforeEach } from 'vitest'
import { Brainy } from '../../src/brainy.js'
import { NounType } from '../../src/types/graphTypes.js'
describe('Brainy 3.0 Core (Unit Tests)', () => {
let brain: Brainy
beforeEach(async () => {
// Create instance with real embeddings for production-ready tests
brain = new Brainy({ requireSubtype: false,
storage: { type: 'memory' }
})
await brain.init()
})
describe('CRUD Operations', () => {
it('should create items with add', async () => {
const id = await brain.add({
data: { name: 'JavaScript', type: 'language' },
type: NounType.Concept,
metadata: { category: 'programming' }
})
expect(id).toBeTypeOf('string')
expect(id.length).toBeGreaterThan(0)
})
it('should retrieve items with get', async () => {
const id = await brain.add({
data: 'Python is a programming language created in 1991',
type: NounType.Concept,
metadata: { name: 'Python', category: 'programming', year: 1991 }
})
const retrieved = await brain.get(id)
expect(retrieved).toBeTruthy()
expect(retrieved?.metadata?.name).toBe('Python')
expect(retrieved?.metadata?.category).toBe('programming')
expect(retrieved?.metadata?.year).toBe(1991)
})
it('should update items with update', async () => {
const id = await brain.add({
data: 'TypeScript is a typed JavaScript superset',
type: NounType.Concept,
metadata: { name: 'TypeScript', version: '4.0', category: 'programming' }
})
await brain.update({
id,
metadata: { version: '5.0', popularity: 'high' }
})
const updated = await brain.get(id)
expect(updated?.metadata?.version).toBe('5.0')
expect(updated?.metadata?.popularity).toBe('high')
expect(updated?.metadata?.name).toBe('TypeScript') // Original metadata preserved
})
it('should delete items with delete', async () => {
const id = await brain.add({
data: { name: 'ToDelete', temp: true },
type: NounType.Concept
})
// Verify it exists
expect(await brain.get(id)).toBeTruthy()
// Delete it
await brain.delete(id)
// Verify it's gone
expect(await brain.get(id)).toBeNull()
})
it('should handle non-existent IDs according to API contract', async () => {
// Use valid UUID format (stricter validation in v5.1.0)
// v5.10.0: Can't use 00000000... anymore (it's the VFS root)
const fakeId = '11111111-1111-1111-1111-111111111111'
expect(await brain.get(fakeId)).toBeNull()
// update should handle non-existent ID gracefully
await expect(brain.update({
id: fakeId,
data: { test: 'data' }
})).rejects.toThrow()
// delete should not throw for non-existent ID
await expect(brain.delete(fakeId)).resolves.not.toThrow()
})
})
describe('Search Operations', () => {
beforeEach(async () => {
// Add test data with real embeddings
await brain.add({
data: { name: 'React', type: 'framework', category: 'frontend' },
type: NounType.Concept,
metadata: { tags: ['ui', 'javascript'] }
})
await brain.add({
data: { name: 'Vue', type: 'framework', category: 'frontend' },
type: NounType.Concept,
metadata: { tags: ['ui', 'javascript'] }
})
await brain.add({
data: { name: 'Express', type: 'framework', category: 'backend' },
type: NounType.Concept,
metadata: { tags: ['server', 'nodejs'] }
})
await brain.add({
data: { name: 'Java', type: 'language', category: 'backend' },
type: NounType.Concept,
metadata: { tags: ['jvm', 'enterprise'] }
})
})
it('should return search results with real embeddings', async () => {
const results = await brain.find({
query: 'frontend framework',
limit: 2
})
expect(results).toBeInstanceOf(Array)
expect(results.length).toBeGreaterThan(0)
expect(results.length).toBeLessThanOrEqual(2)
// Results should have required properties
results.forEach((result: any) => {
expect(result).toHaveProperty('id')
expect(result).toHaveProperty('score')
expect(result).toHaveProperty('entity')
})
})
it('should handle limit parameter', async () => {
const limitedResults = await brain.find({
query: 'framework',
limit: 2
})
const unlimitedResults = await brain.find({
query: 'framework',
limit: 10
})
expect(limitedResults.length).toBeLessThanOrEqual(2)
expect(unlimitedResults.length).toBeLessThanOrEqual(10)
})
it('should search by metadata filters', async () => {
const results = await brain.find({
where: { category: 'frontend' },
limit: 10
})
expect(results).toBeInstanceOf(Array)
// All results should have frontend category
results.forEach((item: any) => {
expect(item.entity.metadata?.category).toBe('frontend')
})
})
it('should handle complex queries with Triple Intelligence', async () => {
const results = await brain.find({
query: 'javascript',
where: { type: 'framework' },
limit: 5,
fusion: {
strategy: 'adaptive',
weights: { vector: 0.6, field: 0.4 }
}
})
expect(results).toBeInstanceOf(Array)
// Results should match both vector similarity and field filters
results.forEach((item: any) => {
expect(item.entity.metadata?.type).toBe('framework')
})
})
})
describe('Statistics and Metadata', () => {
it('should track statistics', async () => {
await brain.add({
data: { name: 'Test1' },
type: NounType.Concept
})
await brain.add({
data: { name: 'Test2' },
type: NounType.Concept
})
// Statistics would be available through augmentation system
// The exact API depends on augmentation configuration
})
})
describe('Clear Operations', () => {
it('should clear all data', async () => {
await brain.add({
data: { name: 'Test1' },
type: NounType.Concept
})
await brain.add({
data: { name: 'Test2' },
type: NounType.Concept
})
await brain.add({
data: { name: 'Test3' },
type: NounType.Concept
})
// Clear everything — entities, relationships, and all indexes
await brain.clear()
// Verify user data is cleared. clear() re-creates a fresh VFS root
// entity, and a thresholdless vector search can surface it — so filter
// VFS bookkeeping out and assert the added entities are gone.
const results = await brain.find({
query: 'Test',
limit: 10
})
const userResults = results.filter(r => !r.metadata?.isVFS)
expect(userResults.length).toBe(0)
})
})
describe('Edge Cases and Error Handling', () => {
it('should handle empty queries gracefully', async () => {
const results = await brain.find({
query: '',
limit: 5
})
expect(results).toBeInstanceOf(Array)
})
it('should handle special characters in data', async () => {
const id = await brain.add({
data: 'Test with special chars: !@#$%^&*()',
type: NounType.Concept,
metadata: { name: 'Test !@#$%^&*()', description: 'Has "quotes" and \'apostrophes\'' }
})
const retrieved = await brain.get(id)
expect(retrieved?.metadata?.name).toContain('!@#$%^&*()')
})
it('should handle very long text', async () => {
const longText = 'x'.repeat(10000)
const id = await brain.add({
data: longText,
type: NounType.Document
})
const retrieved = await brain.get(id)
expect(retrieved?.data).toHaveLength(10000)
})
})
})