2
0
mirror of https://github.com/frappe/books.git synced 2024-12-23 11:29:03 +00:00

Merge pull request #491 from 18alantom/update-tests

refactor: mocha → tape
This commit is contained in:
Alan 2022-10-31 01:38:26 -07:00 committed by GitHub
commit f281c891e8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 1468 additions and 1268 deletions

View File

@ -1,10 +1,6 @@
name: Build name: Build
on: on:
push:
branches: [$default-branch]
paths-ignore:
- '**.md'
pull_request: pull_request:
paths-ignore: paths-ignore:
- '**.md' - '**.md'
@ -25,7 +21,7 @@ jobs:
- name: Checkout Books - name: Checkout Books
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Setup Books - name: Install Dependencies
run: yarn run: yarn
- name: Install RPM - name: Install RPM

View File

@ -14,7 +14,7 @@ jobs:
- name: Checkout Books - name: Checkout Books
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Setup Books - name: Install Dependencies
run: | run: |
yarn set version 1.22.18 yarn set version 1.22.18
yarn yarn
@ -65,7 +65,7 @@ jobs:
- name: Checkout Books - name: Checkout Books
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Setup Books - name: Install Dependencies
run: | run: |
yarn set version 1.22.18 yarn set version 1.22.18
yarn yarn
@ -113,7 +113,7 @@ jobs:
- name: Checkout Books - name: Checkout Books
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Setup Books - name: Install Dependencies
run: yarn run: yarn
- name: Set Error Log Creds - name: Set Error Log Creds

32
.github/workflows/test.yml vendored Normal file
View File

@ -0,0 +1,32 @@
name: Test
on:
push:
branches: [$default-branch]
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'
workflow_dispatch:
jobs:
setup_and_test:
runs-on: macos-11
steps:
- name: Setup node
uses: actions/setup-node@v2
with:
node-version: '16.13.1'
- name: Set yarn version
run: yarn set version 1.22.18
- name: Checkout Books
uses: actions/checkout@v2
- name: Install Dependencies
run: yarn
- name: Yarn Tests
run: yarn test

View File

@ -1,6 +1,5 @@
import * as assert from 'assert';
import 'mocha';
import { FieldTypeEnum, RawValue, Schema } from 'schemas/types'; import { FieldTypeEnum, RawValue, Schema } from 'schemas/types';
import test from 'tape';
import { getMapFromList, getValueMapFromList, sleep } from 'utils'; import { getMapFromList, getValueMapFromList, sleep } from 'utils';
import { getDefaultMetaFieldValueMap, sqliteTypeMap } from '../../helpers'; import { getDefaultMetaFieldValueMap, sqliteTypeMap } from '../../helpers';
import DatabaseCore from '../core'; import DatabaseCore from '../core';
@ -9,7 +8,7 @@ import {
assertDoesNotThrow, assertDoesNotThrow,
assertThrows, assertThrows,
BaseMetaKey, BaseMetaKey,
getBuiltTestSchemaMap, getBuiltTestSchemaMap
} from './helpers'; } from './helpers';
/** /**
@ -23,54 +22,50 @@ import {
* This also implies that assert calls should have discriptive * This also implies that assert calls should have discriptive
*/ */
describe('DatabaseCore: Connect Migrate Close', function () { const schemaMap = getBuiltTestSchemaMap();
async function getDb(shouldMigrate: boolean = true): Promise<DatabaseCore> {
const db = new DatabaseCore(); const db = new DatabaseCore();
specify('dbPath', function () {
assert.strictEqual(db.dbPath, ':memory:');
});
const schemaMap = getBuiltTestSchemaMap();
db.setSchemaMap(schemaMap);
specify('schemaMap', function () {
assert.strictEqual(schemaMap, db.schemaMap);
});
specify('connect', async function () {
await assertDoesNotThrow(async () => await db.connect());
assert.notStrictEqual(db.knex, undefined);
});
specify('migrate and close', async function () {
// Does not throw
await db.migrate();
// Does not throw
await db.close();
});
});
describe('DatabaseCore: Migrate and Check Db', function () {
let db: DatabaseCore;
const schemaMap = getBuiltTestSchemaMap();
this.beforeEach(async function () {
db = new DatabaseCore();
await db.connect(); await db.connect();
db.setSchemaMap(schemaMap); db.setSchemaMap(schemaMap);
}); if (shouldMigrate) {
await db.migrate();
}
return db;
}
this.afterEach(async function () { test('db init, migrate, close', async (t) => {
await db.close(); const db = new DatabaseCore();
}); t.equal(db.dbPath, ':memory:');
specify(`Pre Migrate TableInfo`, async function () { const schemaMap = getBuiltTestSchemaMap();
db.setSchemaMap(schemaMap);
// Same Object
t.equal(schemaMap, db.schemaMap);
await assertDoesNotThrow(async () => await db.connect());
t.notEqual(db.knex, undefined);
await assertDoesNotThrow(async () => await db.migrate());
await assertDoesNotThrow(async () => await db.close());
});
/**
* DatabaseCore: Migrate and Check Db
*/
test(`Pre Migrate TableInfo`, async function (t) {
const db = await getDb(false);
for (const schemaName in schemaMap) { for (const schemaName in schemaMap) {
const columns = await db.knex?.raw('pragma table_info(??)', schemaName); const columns = await db.knex?.raw('pragma table_info(??)', schemaName);
assert.strictEqual(columns.length, 0, `column count ${schemaName}`); t.equal(columns.length, 0, `column count ${schemaName}`);
} }
}); await db.close();
});
specify('Post Migrate TableInfo', async function () { test('Post Migrate TableInfo', async function (t) {
await db.migrate(); const db = await getDb();
for (const schemaName in schemaMap) { for (const schemaName in schemaMap) {
const schema = schemaMap[schemaName] as Schema; const schema = schemaMap[schemaName] as Schema;
const fieldMap = getMapFromList(schema.fields, 'fieldname'); const fieldMap = getMapFromList(schema.fields, 'fieldname');
@ -87,7 +82,7 @@ describe('DatabaseCore: Migrate and Check Db', function () {
columnCount = 0; columnCount = 0;
} }
assert.strictEqual( t.equal(
columns.length, columns.length,
columnCount, columnCount,
`${schemaName}:: column count: ${columns.length}, ${columnCount}` `${schemaName}:: column count: ${columns.length}, ${columnCount}`
@ -97,26 +92,26 @@ describe('DatabaseCore: Migrate and Check Db', function () {
const field = fieldMap[column.name]; const field = fieldMap[column.name];
const dbColType = sqliteTypeMap[field.fieldtype]; const dbColType = sqliteTypeMap[field.fieldtype];
assert.strictEqual( t.equal(
column.name, column.name,
field.fieldname, field.fieldname,
`${schemaName}.${column.name}:: name check: ${column.name}, ${field.fieldname}` `${schemaName}.${column.name}:: name check: ${column.name}, ${field.fieldname}`
); );
assert.strictEqual( t.equal(
column.type.toLowerCase(), column.type.toLowerCase(),
dbColType, dbColType,
`${schemaName}.${column.name}:: type check: ${column.type}, ${dbColType}` `${schemaName}.${column.name}:: type check: ${column.type}, ${dbColType}`
); );
if (field.required !== undefined) { if (field.required !== undefined) {
assert.strictEqual( t.equal(
!!column.notnull, !!column.notnull,
field.required, field.required,
`${schemaName}.${column.name}:: iotnull iheck: ${column.notnull}, ${field.required}` `${schemaName}.${column.name}:: iotnull iheck: ${column.notnull}, ${field.required}`
); );
} else { } else {
assert.strictEqual( t.equal(
column.notnull, column.notnull,
0, 0,
`${schemaName}.${column.name}:: notnull check: ${column.notnull}, ${field.required}` `${schemaName}.${column.name}:: notnull check: ${column.notnull}, ${field.required}`
@ -124,13 +119,13 @@ describe('DatabaseCore: Migrate and Check Db', function () {
} }
if (column.dflt_value === null) { if (column.dflt_value === null) {
assert.strictEqual( t.equal(
field.default, field.default,
undefined, undefined,
`${schemaName}.${column.name}:: dflt_value check: ${column.dflt_value}, ${field.default}` `${schemaName}.${column.name}:: dflt_value check: ${column.dflt_value}, ${field.default}`
); );
} else { } else {
assert.strictEqual( t.equal(
column.dflt_value.slice(1, -1), column.dflt_value.slice(1, -1),
String(field.default), String(field.default),
`${schemaName}.${column.name}:: dflt_value check: ${column.type}, ${dbColType}` `${schemaName}.${column.name}:: dflt_value check: ${column.type}, ${dbColType}`
@ -138,36 +133,25 @@ describe('DatabaseCore: Migrate and Check Db', function () {
} }
} }
} }
});
await db.close();
}); });
describe('DatabaseCore: CRUD', function () { test('exists() before insertion', async function (t) {
let db: DatabaseCore; const db = await getDb();
const schemaMap = getBuiltTestSchemaMap();
this.beforeEach(async function () {
db = new DatabaseCore();
await db.connect();
db.setSchemaMap(schemaMap);
await db.migrate();
});
this.afterEach(async function () {
await db.close();
});
specify('exists() before insertion', async function () {
for (const schemaName in schemaMap) { for (const schemaName in schemaMap) {
const doesExist = await db.exists(schemaName); const doesExist = await db.exists(schemaName);
if (['SingleValue', 'SystemSettings'].includes(schemaName)) { if (['SingleValue', 'SystemSettings'].includes(schemaName)) {
assert.strictEqual(doesExist, true, `${schemaName} exists`); t.equal(doesExist, true, `${schemaName} exists`);
} else { } else {
assert.strictEqual(doesExist, false, `${schemaName} exists`); t.equal(doesExist, false, `${schemaName} exists`);
} }
} }
}); await db.close();
});
specify('CRUD single values', async function () { test('CRUD single values', async function (t) {
const db = await getDb();
/** /**
* Checking default values which are created when db.migrate * Checking default values which are created when db.migrate
* takes place. * takes place.
@ -181,7 +165,7 @@ describe('DatabaseCore: CRUD', function () {
'default' 'default'
); );
for (const row of rows) { for (const row of rows) {
assert.strictEqual( t.equal(
row.value, row.value,
defaultMap[row.fieldname as string], defaultMap[row.fieldname as string],
`${row.fieldname} default values equality` `${row.fieldname} default values equality`
@ -203,19 +187,15 @@ describe('DatabaseCore: CRUD', function () {
rows = await db.knex!.raw('select * from SingleValue'); rows = await db.knex!.raw('select * from SingleValue');
localeRow = rows.find((r) => r.fieldname === 'locale'); localeRow = rows.find((r) => r.fieldname === 'locale');
assert.notStrictEqual(localeEntryName, undefined, 'localeEntryName'); t.notEqual(localeEntryName, undefined, 'localeEntryName');
assert.strictEqual(rows.length, 2, 'rows length insert'); t.equal(rows.length, 2, 'rows length insert');
assert.strictEqual( t.equal(
localeRow?.name as string, localeRow?.name as string,
localeEntryName, localeEntryName,
`localeEntryName ${localeRow?.name}, ${localeEntryName}` `localeEntryName ${localeRow?.name}, ${localeEntryName}`
); );
assert.strictEqual( t.equal(localeRow?.value, locale, `locale ${localeRow?.value}, ${locale}`);
localeRow?.value, t.equal(
locale,
`locale ${localeRow?.value}, ${locale}`
);
assert.strictEqual(
localeRow?.created, localeRow?.created,
localeEntryCreated, localeEntryCreated,
`locale ${localeRow?.value}, ${locale}` `locale ${localeRow?.value}, ${locale}`
@ -229,19 +209,15 @@ describe('DatabaseCore: CRUD', function () {
rows = await db.knex!.raw('select * from SingleValue'); rows = await db.knex!.raw('select * from SingleValue');
localeRow = rows.find((r) => r.fieldname === 'locale'); localeRow = rows.find((r) => r.fieldname === 'locale');
assert.notStrictEqual(localeEntryName, undefined, 'localeEntryName'); t.notEqual(localeEntryName, undefined, 'localeEntryName');
assert.strictEqual(rows.length, 2, 'rows length update'); t.equal(rows.length, 2, 'rows length update');
assert.strictEqual( t.equal(
localeRow?.name as string, localeRow?.name as string,
localeEntryName, localeEntryName,
`localeEntryName ${localeRow?.name}, ${localeEntryName}` `localeEntryName ${localeRow?.name}, ${localeEntryName}`
); );
assert.strictEqual( t.equal(localeRow?.value, locale, `locale ${localeRow?.value}, ${locale}`);
localeRow?.value, t.equal(
locale,
`locale ${localeRow?.value}, ${locale}`
);
assert.strictEqual(
localeRow?.created, localeRow?.created,
localeEntryCreated, localeEntryCreated,
`locale ${localeRow?.value}, ${locale}` `locale ${localeRow?.value}, ${locale}`
@ -252,15 +228,15 @@ describe('DatabaseCore: CRUD', function () {
*/ */
await db.delete('SystemSettings', 'locale'); await db.delete('SystemSettings', 'locale');
rows = await db.knex!.raw('select * from SingleValue'); rows = await db.knex!.raw('select * from SingleValue');
assert.strictEqual(rows.length, 1, 'delete one'); t.equal(rows.length, 1, 'delete one');
await db.delete('SystemSettings', 'dateFormat'); await db.delete('SystemSettings', 'dateFormat');
rows = await db.knex!.raw('select * from SingleValue'); rows = await db.knex!.raw('select * from SingleValue');
assert.strictEqual(rows.length, 0, 'delete two'); t.equal(rows.length, 0, 'delete two');
const dateFormat = 'dd/mm/yy'; const dateFormat = 'dd/mm/yy';
await db.insert('SystemSettings', { locale, dateFormat }); await db.insert('SystemSettings', { locale, dateFormat });
rows = await db.knex!.raw('select * from SingleValue'); rows = await db.knex!.raw('select * from SingleValue');
assert.strictEqual(rows.length, 2, 'delete two'); t.equal(rows.length, 2, 'delete two');
/** /**
* Read * Read
@ -268,14 +244,10 @@ describe('DatabaseCore: CRUD', function () {
* getSingleValues * getSingleValues
*/ */
const svl = await db.getSingleValues('locale', 'dateFormat'); const svl = await db.getSingleValues('locale', 'dateFormat');
assert.strictEqual(svl.length, 2, 'getSingleValues length'); t.equal(svl.length, 2, 'getSingleValues length');
for (const sv of svl) { for (const sv of svl) {
assert.strictEqual( t.equal(sv.parent, 'SystemSettings', `singleValue parent ${sv.parent}`);
sv.parent, t.equal(
'SystemSettings',
`singleValue parent ${sv.parent}`
);
assert.strictEqual(
sv.value, sv.value,
{ locale, dateFormat }[sv.fieldname], { locale, dateFormat }[sv.fieldname],
`singleValue value ${sv.value}` `singleValue value ${sv.value}`
@ -285,16 +257,19 @@ describe('DatabaseCore: CRUD', function () {
* get * get
*/ */
const svlMap = await db.get('SystemSettings'); const svlMap = await db.get('SystemSettings');
assert.strictEqual(Object.keys(svlMap).length, 2, 'get key length'); t.equal(Object.keys(svlMap).length, 2, 'get key length');
assert.strictEqual(svlMap.locale, locale, 'get locale'); t.equal(svlMap.locale, locale, 'get locale');
assert.strictEqual(svlMap.dateFormat, dateFormat, 'get locale'); t.equal(svlMap.dateFormat, dateFormat, 'get locale');
} }
});
specify('CRUD nondependent schema', async function () { await db.close();
});
test('CRUD nondependent schema', async function (t) {
const db = await getDb();
const schemaName = 'Customer'; const schemaName = 'Customer';
let rows = await db.knex!(schemaName); let rows = await db.knex!(schemaName);
assert.strictEqual(rows.length, 0, 'rows length before insertion'); t.equal(rows.length, 0, 'rows length before insertion');
/** /**
* Insert * Insert
@ -311,20 +286,12 @@ describe('DatabaseCore: CRUD', function () {
await db.insert(schemaName, updateMap); await db.insert(schemaName, updateMap);
rows = await db.knex!(schemaName); rows = await db.knex!(schemaName);
let firstRow = rows?.[0]; let firstRow = rows?.[0];
assert.strictEqual(rows.length, 1, `rows length insert ${rows.length}`); t.equal(rows.length, 1, `rows length insert ${rows.length}`);
assert.strictEqual( t.equal(firstRow.name, name, `name check ${firstRow.name}, ${name}`);
firstRow.name, t.equal(firstRow.email, null, `email check ${firstRow.email}`);
name,
`name check ${firstRow.name}, ${name}`
);
assert.strictEqual(firstRow.email, null, `email check ${firstRow.email}`);
for (const key in metaValues) { for (const key in metaValues) {
assert.strictEqual( t.equal(firstRow[key], metaValues[key as BaseMetaKey], `${key} check`);
firstRow[key],
metaValues[key as BaseMetaKey],
`${key} check`
);
} }
/** /**
@ -339,17 +306,9 @@ describe('DatabaseCore: CRUD', function () {
}); });
rows = await db.knex!(schemaName); rows = await db.knex!(schemaName);
firstRow = rows?.[0]; firstRow = rows?.[0];
assert.strictEqual(rows.length, 1, `rows length update ${rows.length}`); t.equal(rows.length, 1, `rows length update ${rows.length}`);
assert.strictEqual( t.equal(firstRow.name, name, `name check update ${firstRow.name}, ${name}`);
firstRow.name, t.equal(firstRow.email, email, `email check update ${firstRow.email}`);
name,
`name check update ${firstRow.name}, ${name}`
);
assert.strictEqual(
firstRow.email,
email,
`email check update ${firstRow.email}`
);
const phone = '8149133530'; const phone = '8149133530';
await sleep(1); await sleep(1);
@ -360,28 +319,16 @@ describe('DatabaseCore: CRUD', function () {
}); });
rows = await db.knex!(schemaName); rows = await db.knex!(schemaName);
firstRow = rows?.[0]; firstRow = rows?.[0];
assert.strictEqual( t.equal(firstRow.email, email, `email check update ${firstRow.email}`);
firstRow.email, t.equal(firstRow.phone, phone, `email check update ${firstRow.phone}`);
email,
`email check update ${firstRow.email}`
);
assert.strictEqual(
firstRow.phone,
phone,
`email check update ${firstRow.phone}`
);
for (const key in metaValues) { for (const key in metaValues) {
const val = firstRow[key]; const val = firstRow[key];
const expected = metaValues[key as BaseMetaKey]; const expected = metaValues[key as BaseMetaKey];
if (key !== 'modified') { if (key !== 'modified') {
assert.strictEqual(val, expected, `${key} check ${val}, ${expected}`); t.equal(val, expected, `${key} check ${val}, ${expected}`);
} else { } else {
assert.notStrictEqual( t.notEqual(val, expected, `${key} check ${val}, ${expected}`);
val,
expected,
`${key} check ${val}, ${expected}`
);
} }
} }
@ -390,13 +337,13 @@ describe('DatabaseCore: CRUD', function () {
*/ */
await db.delete(schemaName, name); await db.delete(schemaName, name);
rows = await db.knex!(schemaName); rows = await db.knex!(schemaName);
assert.strictEqual(rows.length, 0, `rows length delete ${rows.length}`); t.equal(rows.length, 0, `rows length delete ${rows.length}`);
/** /**
* Get * Get
*/ */
let fvMap = await db.get(schemaName, name); let fvMap = await db.get(schemaName, name);
assert.strictEqual( t.equal(
Object.keys(fvMap).length, Object.keys(fvMap).length,
0, 0,
`key count get ${JSON.stringify(fvMap)}` `key count get ${JSON.stringify(fvMap)}`
@ -411,20 +358,16 @@ describe('DatabaseCore: CRUD', function () {
// Insert // Insert
await db.insert(schemaName, cOne); await db.insert(schemaName, cOne);
assert.strictEqual( t.equal((await db.knex!(schemaName)).length, 1, `rows length minsert`);
(await db.knex!(schemaName)).length,
1,
`rows length minsert`
);
await db.insert(schemaName, cTwo); await db.insert(schemaName, cTwo);
rows = await db.knex!(schemaName); rows = await db.knex!(schemaName);
assert.strictEqual(rows.length, 2, `rows length minsert`); t.equal(rows.length, 2, `rows length minsert`);
const cs = [cOne, cTwo]; const cs = [cOne, cTwo];
for (const i in cs) { for (const i in cs) {
for (const k in cs[i]) { for (const k in cs[i]) {
const val = cs[i][k as BaseMetaKey]; const val = cs[i][k as BaseMetaKey];
assert.strictEqual( t.equal(
rows?.[i]?.[k], rows?.[i]?.[k],
val, val,
`equality check ${i} ${k} ${val} ${rows?.[i]?.[k]}` `equality check ${i} ${k} ${val} ${rows?.[i]?.[k]}`
@ -435,48 +378,35 @@ describe('DatabaseCore: CRUD', function () {
// Update // Update
await db.update(schemaName, { name: cOne.name, email }); await db.update(schemaName, { name: cOne.name, email });
const cOneEmail = await db.get(schemaName, cOne.name, 'email'); const cOneEmail = await db.get(schemaName, cOne.name, 'email');
assert.strictEqual( t.equal(cOneEmail.email, email, `mi update check one ${cOneEmail}`);
cOneEmail.email,
email,
`mi update check one ${cOneEmail}`
);
const cTwoEmail = await db.get(schemaName, cTwo.name, 'email'); const cTwoEmail = await db.get(schemaName, cTwo.name, 'email');
assert.strictEqual( t.equal(cOneEmail.email, email, `mi update check two ${cTwoEmail}`);
cOneEmail.email,
email,
`mi update check two ${cTwoEmail}`
);
// Rename // Rename
const newName = 'Johnny Whoe'; const newName = 'Johnny Whoe';
await db.rename(schemaName, cOne.name, newName); await db.rename(schemaName, cOne.name, newName);
fvMap = await db.get(schemaName, cOne.name); fvMap = await db.get(schemaName, cOne.name);
assert.strictEqual( t.equal(
Object.keys(fvMap).length, Object.keys(fvMap).length,
0, 0,
`mi rename check old ${JSON.stringify(fvMap)}` `mi rename check old ${JSON.stringify(fvMap)}`
); );
fvMap = await db.get(schemaName, newName); fvMap = await db.get(schemaName, newName);
assert.strictEqual( t.equal(fvMap.email, email, `mi rename check new ${JSON.stringify(fvMap)}`);
fvMap.email,
email,
`mi rename check new ${JSON.stringify(fvMap)}`
);
// Delete // Delete
await db.delete(schemaName, newName); await db.delete(schemaName, newName);
rows = await db.knex!(schemaName); rows = await db.knex!(schemaName);
assert.strictEqual(rows.length, 1, `mi delete length ${rows.length}`); t.equal(rows.length, 1, `mi delete length ${rows.length}`);
assert.strictEqual( t.equal(rows[0].name, cTwo.name, `mi delete name ${rows[0].name}`);
rows[0].name, await db.close();
cTwo.name, });
`mi delete name ${rows[0].name}`
); test('CRUD dependent schema', async function (t) {
}); const db = await getDb();
specify('CRUD dependent schema', async function () {
const Customer = 'Customer'; const Customer = 'Customer';
const SalesInvoice = 'SalesInvoice'; const SalesInvoice = 'SalesInvoice';
const SalesInvoiceItem = 'SalesInvoiceItem'; const SalesInvoiceItem = 'SalesInvoiceItem';
@ -527,18 +457,14 @@ describe('DatabaseCore: CRUD', function () {
expected = +expected; expected = +expected;
} }
assert.strictEqual( t.equal(
fvMap[key], fvMap[key],
expected, expected,
`equality check ${key}: ${fvMap[key]}, ${invoice[key]}` `equality check ${key}: ${fvMap[key]}, ${invoice[key]}`
); );
} }
assert.strictEqual( t.equal((fvMap.items as unknown[])?.length, 0, 'empty items check');
(fvMap.items as unknown[])?.length,
0,
'empty items check'
);
const items: FieldValueMap[] = [ const items: FieldValueMap[] = [
{ {
@ -560,20 +486,20 @@ describe('DatabaseCore: CRUD', function () {
fvMap = await db.get(SalesInvoice, invoice.name as string); fvMap = await db.get(SalesInvoice, invoice.name as string);
const ct = fvMap.items as FieldValueMap[]; const ct = fvMap.items as FieldValueMap[];
assert.strictEqual(ct.length, 1, `ct length ${ct.length}`); t.equal(ct.length, 1, `ct length ${ct.length}`);
assert.strictEqual(ct[0].parent, invoice.name, `ct parent ${ct[0].parent}`); t.equal(ct[0].parent, invoice.name, `ct parent ${ct[0].parent}`);
assert.strictEqual( t.equal(
ct[0].parentFieldname, ct[0].parentFieldname,
'items', 'items',
`ct parentFieldname ${ct[0].parentFieldname}` `ct parentFieldname ${ct[0].parentFieldname}`
); );
assert.strictEqual( t.equal(
ct[0].parentSchemaName, ct[0].parentSchemaName,
SalesInvoice, SalesInvoice,
`ct parentSchemaName ${ct[0].parentSchemaName}` `ct parentSchemaName ${ct[0].parentSchemaName}`
); );
for (const key in items[0]) { for (const key in items[0]) {
assert.strictEqual( t.equal(
ct[0][key], ct[0][key],
items[0][key], items[0][key],
`ct values ${key}: ${ct[0][key]}, ${items[0][key]}` `ct values ${key}: ${ct[0][key]}, ${items[0][key]}`
@ -594,11 +520,11 @@ describe('DatabaseCore: CRUD', function () {
let rows = await db.getAll(SalesInvoiceItem, { let rows = await db.getAll(SalesInvoiceItem, {
fields: ['item', 'quantity', 'rate', 'amount'], fields: ['item', 'quantity', 'rate', 'amount'],
}); });
assert.strictEqual(rows.length, 2, `ct length update ${rows.length}`); t.equal(rows.length, 2, `ct length update ${rows.length}`);
for (const i in rows) { for (const i in rows) {
for (const key in rows[i]) { for (const key in rows[i]) {
assert.strictEqual( t.equal(
rows[i][key], rows[i][key],
items[i][key], items[i][key],
`ct values ${i},${key}: ${rows[i][key]}` `ct values ${i},${key}: ${rows[i][key]}`
@ -615,10 +541,11 @@ describe('DatabaseCore: CRUD', function () {
}); });
rows = await db.knex!(SalesInvoiceItem); rows = await db.knex!(SalesInvoiceItem);
assert.strictEqual(rows.length, 2, `postupdate ct empty ${rows.length}`); t.equal(rows.length, 2, `postupdate ct empty ${rows.length}`);
await db.delete(SalesInvoice, invoice.name as string); await db.delete(SalesInvoice, invoice.name as string);
rows = await db.getAll(SalesInvoiceItem); rows = await db.getAll(SalesInvoiceItem);
assert.strictEqual(rows.length, 0, `ct length delete ${rows.length}`); t.equal(rows.length, 0, `ct length delete ${rows.length}`);
});
await db.close();
}); });

View File

@ -1,49 +1,27 @@
import * as assert from 'assert';
import { DatabaseManager } from 'backend/database/manager';
import { assertDoesNotThrow } from 'backend/database/tests/helpers'; import { assertDoesNotThrow } from 'backend/database/tests/helpers';
import { purchaseItemPartyMap } from 'dummy/helpers'; import { purchaseItemPartyMap } from 'dummy/helpers';
import { Fyo } from 'fyo'; import test from 'tape';
import { DummyAuthDemux } from 'fyo/tests/helpers'; import { getTestDbPath, getTestFyo } from 'tests/helpers';
import 'mocha';
import { getTestDbPath } from 'tests/helpers';
import { setupDummyInstance } from '..'; import { setupDummyInstance } from '..';
describe('dummy', function () { const dbPath = getTestDbPath();
const dbPath = getTestDbPath(); const fyo = getTestFyo();
let fyo: Fyo; test('setupDummyInstance', async () => {
this.beforeAll(function () {
fyo = new Fyo({
DatabaseDemux: DatabaseManager,
AuthDemux: DummyAuthDemux,
isTest: true,
isElectron: false,
});
});
this.afterAll(async function () {
await fyo.close();
});
specify('setupDummyInstance', async function () {
await assertDoesNotThrow(async () => { await assertDoesNotThrow(async () => {
await setupDummyInstance(dbPath, fyo, 1, 25); await setupDummyInstance(dbPath, fyo, 1, 25);
}, 'setup instance failed'); }, 'setup instance failed');
});
test('purchaseItemParty Existance', async (t) => {
for (const item in purchaseItemPartyMap) { for (const item in purchaseItemPartyMap) {
assert.strictEqual( t.ok(await fyo.db.exists('Item', item), `item exists: ${item}`);
await fyo.db.exists('Item', item),
true,
`not found ${item}`
);
const party = purchaseItemPartyMap[item]; const party = purchaseItemPartyMap[item];
assert.strictEqual( t.ok(await fyo.db.exists('Party', party), `party exists: ${party}`);
await fyo.db.exists('Party', party),
true,
`not found ${party}`
);
} }
}).timeout(120_000); });
test.onFinish(async () => {
await fyo.close();
}); });

View File

@ -1,64 +1,27 @@
import * as assert from 'assert';
import 'mocha';
import { getRegionalModels, models } from 'models'; import { getRegionalModels, models } from 'models';
import { getSchemas } from 'schemas'; import { getSchemas } from 'schemas';
import { Fyo } from '..'; import test from 'tape';
import { DatabaseManager } from '../../backend/database/manager'; import { getTestFyo } from 'tests/helpers';
import { DummyAuthDemux } from './helpers';
describe('Fyo Init', function () { test('Fyo Init', async (t) => {
const fyo = new Fyo({ const fyo = getTestFyo();
DatabaseDemux: DatabaseManager, t.equal(Object.keys(fyo.schemaMap).length, 0, 'zero schemas');
AuthDemux: DummyAuthDemux,
isTest: true,
isElectron: false,
});
specify('Init', async function () {
assert.strictEqual(
Object.keys(fyo.schemaMap).length,
0,
'zero schemas one'
);
assert.strictEqual(
Object.keys(fyo.schemaMap).length,
0,
'zero schemas two'
);
await fyo.db.createNewDatabase(':memory:', 'in'); await fyo.db.createNewDatabase(':memory:', 'in');
await fyo.initializeAndRegister({}, {}); await fyo.initializeAndRegister({}, {});
assert.strictEqual(
Object.keys(fyo.schemaMap).length > 0, t.equal(Object.keys(fyo.schemaMap).length > 0, true, 'non zero schemas');
true, await fyo.close();
'non zero schemas'
);
await fyo.db.purgeCache();
});
}); });
describe('Fyo Docs', function () { test('Fyo Docs', async (t) => {
const countryCode = 'in'; const countryCode = 'in';
let fyo: Fyo; const fyo = getTestFyo();
const schemaMap = getSchemas(countryCode); const schemaMap = getSchemas(countryCode);
this.beforeEach(async function () {
fyo = new Fyo({
DatabaseDemux: DatabaseManager,
isTest: true,
isElectron: false,
});
const regionalModels = await getRegionalModels(countryCode); const regionalModels = await getRegionalModels(countryCode);
await fyo.db.createNewDatabase(':memory:', countryCode); await fyo.db.createNewDatabase(':memory:', countryCode);
await fyo.initializeAndRegister(models, regionalModels); await fyo.initializeAndRegister(models, regionalModels);
});
this.afterEach(async function () {
await fyo.close();
});
specify('getNewDoc', async function () {
for (const schemaName in schemaMap) { for (const schemaName in schemaMap) {
const schema = schemaMap[schemaName]; const schema = schemaMap[schemaName];
if (schema?.isSingle) { if (schema?.isSingle) {
@ -66,6 +29,8 @@ describe('Fyo Docs', function () {
} }
const doc = fyo.doc.getNewDoc(schemaName); const doc = fyo.doc.getNewDoc(schemaName);
t.equal(doc.schemaName, schemaName, `equal schemaNames: ${schemaName}`);
} }
});
await fyo.close();
}); });

View File

@ -1,131 +1,84 @@
import * as assert from 'assert'; import { strictEqual } from 'assert';
import Observable from 'fyo/utils/observable'; import Observable from 'fyo/utils/observable';
import 'mocha'; import test from 'tape';
enum ObsEvent { enum ObsEvent {
A = 'event-a', A = 'event-a',
B = 'event-b', B = 'event-b',
} }
describe('Observable', function () { const obs = new Observable();
const obs = new Observable(); let counter = 0;
let counter = 0; const params = { aOne: 18, aTwo: 21, b: 42 };
const params = { aOne: 18, aTwo: 21, b: 42 };
const listenerAOnce = (value: number) => { const listenerAOnce = (value: number) => {
assert.strictEqual(params.aOne, value, 'listenerAOnce'); strictEqual(params.aOne, value, 'listenerAOnce');
}; };
const listenerAEvery = (value: number) => { const listenerAEvery = (value: number) => {
if (counter === 0) { if (counter === 0) {
assert.strictEqual(params.aOne, value, 'listenerAEvery 0'); strictEqual(params.aOne, value, 'listenerAEvery 0');
} else if (counter === 1) { } else if (counter === 1) {
assert.strictEqual(params.aTwo, value, 'listenerAEvery 1'); strictEqual(params.aTwo, value, 'listenerAEvery 1');
} else { } else {
throw new Error("this shouldn't run"); throw new Error("this shouldn't run");
} }
counter += 1; counter += 1;
}; };
const listenerBOnce = (value: number) => { const listenerBOnce = (value: number) => {
assert.strictEqual(params.b, value, 'listenerBOnce'); strictEqual(params.b, value, 'listenerBOnce');
}; };
specify('set A One', function () { test('set A One', function (t) {
assert.strictEqual(obs.hasListener(ObsEvent.A), false, 'pre'); t.equal(obs.hasListener(ObsEvent.A), false, 'pre');
obs.once(ObsEvent.A, listenerAOnce); obs.once(ObsEvent.A, listenerAOnce);
assert.strictEqual(obs.hasListener(ObsEvent.A), true, 'non specific'); t.equal(obs.hasListener(ObsEvent.A), true, 'non specific');
assert.strictEqual( t.equal(obs.hasListener(ObsEvent.A, listenerAOnce), true, 'specific once');
obs.hasListener(ObsEvent.A, listenerAOnce), t.equal(obs.hasListener(ObsEvent.A, listenerAEvery), false, 'specific every');
true, t.end()
'specific once' });
);
assert.strictEqual(
obs.hasListener(ObsEvent.A, listenerAEvery),
false,
'specific every'
);
});
specify('set A Two', function () { test('set A Two', function (t) {
obs.on(ObsEvent.A, listenerAEvery); obs.on(ObsEvent.A, listenerAEvery);
assert.strictEqual(obs.hasListener(ObsEvent.A), true, 'non specific'); t.equal(obs.hasListener(ObsEvent.A), true, 'non specific');
assert.strictEqual( t.equal(obs.hasListener(ObsEvent.A, listenerAOnce), true, 'specific once');
obs.hasListener(ObsEvent.A, listenerAOnce), t.equal(obs.hasListener(ObsEvent.A, listenerAEvery), true, 'specific every');
true, t.end()
'specific once' });
);
assert.strictEqual(
obs.hasListener(ObsEvent.A, listenerAEvery),
true,
'specific every'
);
});
specify('set B', function () { test('set B', function (t) {
assert.strictEqual(obs.hasListener(ObsEvent.B), false, 'pre'); t.equal(obs.hasListener(ObsEvent.B), false, 'pre');
obs.once(ObsEvent.B, listenerBOnce); obs.once(ObsEvent.B, listenerBOnce);
assert.strictEqual( t.equal(obs.hasListener(ObsEvent.A, listenerBOnce), false, 'specific false');
obs.hasListener(ObsEvent.A, listenerBOnce), t.equal(obs.hasListener(ObsEvent.B, listenerBOnce), true, 'specific true');
false, t.end()
'specific false' });
);
assert.strictEqual( test('trigger A 0', async function (t) {
obs.hasListener(ObsEvent.B, listenerBOnce), await obs.trigger(ObsEvent.A, params.aOne);
true, t.equal(obs.hasListener(ObsEvent.A), true, 'non specific');
'specific true' t.equal(obs.hasListener(ObsEvent.A, listenerAOnce), false, 'specific');
); });
});
test('trigger A 1', async function (t) {
specify('trigger A 0', async function () { t.equal(obs.hasListener(ObsEvent.A, listenerAEvery), true, 'specific pre');
await obs.trigger(ObsEvent.A, params.aOne); await obs.trigger(ObsEvent.A, params.aTwo);
assert.strictEqual(obs.hasListener(ObsEvent.A), true, 'non specific'); t.equal(obs.hasListener(ObsEvent.A, listenerAEvery), true, 'specific post');
assert.strictEqual( });
obs.hasListener(ObsEvent.A, listenerAOnce),
false, test('trigger B', async function (t) {
'specific' t.equal(obs.hasListener(ObsEvent.B, listenerBOnce), true, 'specific pre');
); await obs.trigger(ObsEvent.B, params.b);
}); t.equal(obs.hasListener(ObsEvent.B, listenerBOnce), false, 'specific post');
});
specify('trigger A 1', async function () {
assert.strictEqual( test('remove A', async function (t) {
obs.hasListener(ObsEvent.A, listenerAEvery), obs.off(ObsEvent.A, listenerAEvery);
true, t.equal(obs.hasListener(ObsEvent.A, listenerAEvery), false, 'specific pre');
'specific pre'
); t.equal(counter, 2, 'incorrect counter');
await obs.trigger(ObsEvent.A, params.aTwo); await obs.trigger(ObsEvent.A, 777);
assert.strictEqual(
obs.hasListener(ObsEvent.A, listenerAEvery),
true,
'specific post'
);
});
specify('trigger B', async function () {
assert.strictEqual(
obs.hasListener(ObsEvent.B, listenerBOnce),
true,
'specific pre'
);
await obs.trigger(ObsEvent.B, params.b);
assert.strictEqual(
obs.hasListener(ObsEvent.B, listenerBOnce),
false,
'specific post'
);
});
specify('remove A', async function () {
obs.off(ObsEvent.A, listenerAEvery);
assert.strictEqual(
obs.hasListener(ObsEvent.A, listenerAEvery),
false,
'specific pre'
);
assert.strictEqual(counter, 2, 'incorrect counter');
await obs.trigger(ObsEvent.A, 777);
});
}); });

View File

@ -17,7 +17,7 @@
"electron:serve": "vue-cli-service electron:serve", "electron:serve": "vue-cli-service electron:serve",
"script:translate": "scripts/runner.sh scripts/generateTranslations.ts", "script:translate": "scripts/runner.sh scripts/generateTranslations.ts",
"script:profile": "scripts/profile.sh", "script:profile": "scripts/profile.sh",
"test": "scripts/runner.sh ./node_modules/.bin/mocha ./**/tests/**/*.spec.ts --exit" "test": "scripts/runner.sh ./node_modules/.bin/tape ./**/tests/**/*.spec.ts | tap-spec"
}, },
"dependencies": { "dependencies": {
"@popperjs/core": "^2.10.2", "@popperjs/core": "^2.10.2",
@ -43,6 +43,7 @@
"@types/mocha": "^9.1.0", "@types/mocha": "^9.1.0",
"@types/node": "^17.0.23", "@types/node": "^17.0.23",
"@types/node-fetch": "^2.6.1", "@types/node-fetch": "^2.6.1",
"@types/tape": "^4.13.2",
"@typescript-eslint/eslint-plugin": "^4.15.1", "@typescript-eslint/eslint-plugin": "^4.15.1",
"@typescript-eslint/parser": "^4.15.1", "@typescript-eslint/parser": "^4.15.1",
"@vue/cli-plugin-babel": "^4.5.0", "@vue/cli-plugin-babel": "^4.5.0",
@ -65,11 +66,12 @@
"eslint-plugin-prettier": "^4.0.0", "eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-vue": "^7.0.0", "eslint-plugin-vue": "^7.0.0",
"lint-staged": "^11.2.6", "lint-staged": "^11.2.6",
"mocha": "^9.2.2",
"postcss": "^8", "postcss": "^8",
"prettier": "^2.4.1", "prettier": "^2.4.1",
"raw-loader": "^4.0.2", "raw-loader": "^4.0.2",
"tailwindcss": "npm:@tailwindcss/postcss7-compat", "tailwindcss": "npm:@tailwindcss/postcss7-compat",
"tap-spec": "^5.0.0",
"tape": "^5.6.1",
"ts-node": "^10.7.0", "ts-node": "^10.7.0",
"tsconfig-paths": "^3.14.1", "tsconfig-paths": "^3.14.1",
"tslib": "^2.3.1", "tslib": "^2.3.1",

View File

@ -1,173 +1,161 @@
import * as assert from 'assert';
import { cloneDeep, isEqual } from 'lodash'; import { cloneDeep, isEqual } from 'lodash';
import { describe } from 'mocha'; import test from 'tape';
import { getMapFromList } from 'utils'; import { getMapFromList } from 'utils';
import { import {
addMetaFields, addMetaFields,
cleanSchemas, cleanSchemas,
getAbstractCombinedSchemas, getAbstractCombinedSchemas,
getRegionalCombinedSchemas, getRegionalCombinedSchemas,
setSchemaNameOnFields, setSchemaNameOnFields
} from '../index'; } from '../index';
import { metaSchemas } from '../schemas'; import { metaSchemas } from '../schemas';
import { import {
everyFieldExists, everyFieldExists,
getTestSchemaMap, getTestSchemaMap,
someFieldExists, someFieldExists,
subtract, subtract
} from './helpers'; } from './helpers';
describe('Schema Builder', function () { const { appSchemaMap, regionalSchemaMap } = getTestSchemaMap();
const { appSchemaMap, regionalSchemaMap } = getTestSchemaMap(); test('Meta Properties', function (t) {
describe('Raw Schemas', function () { t.equal(appSchemaMap.Party.isAbstract, true);
specify('Meta Properties', function () { t.equal(appSchemaMap.Customer.extends, 'Party');
assert.strictEqual(appSchemaMap.Party.isAbstract, true); t.equal(appSchemaMap.Account.isTree, true);
assert.strictEqual(appSchemaMap.Customer.extends, 'Party'); t.equal(appSchemaMap.JournalEntryAccount.isChild, true);
assert.strictEqual(appSchemaMap.Account.isTree, true); t.end();
assert.strictEqual(appSchemaMap.JournalEntryAccount.isChild, true); });
});
specify('Field Counts', function () { test('Field Counts', function (t) {
assert.strictEqual(appSchemaMap.Account.fields?.length, 6); t.equal(appSchemaMap.Account.fields?.length, 6);
assert.strictEqual(appSchemaMap.JournalEntry.fields?.length, 9); t.equal(appSchemaMap.JournalEntry.fields?.length, 9);
assert.strictEqual(appSchemaMap.JournalEntryAccount.fields?.length, 3); t.equal(appSchemaMap.JournalEntryAccount.fields?.length, 3);
assert.strictEqual(appSchemaMap.Party.fields?.length, 9); t.equal(appSchemaMap.Party.fields?.length, 9);
assert.strictEqual(appSchemaMap.Customer.fields?.length, undefined); t.equal(appSchemaMap.Customer.fields?.length, undefined);
assert.strictEqual(regionalSchemaMap.Party.fields?.length, 2); t.equal(regionalSchemaMap.Party.fields?.length, 2);
}); t.end();
});
specify('Quick Edit Field Counts', function () { test('Quick Edit Field Counts', function (t) {
assert.strictEqual(appSchemaMap.Party.quickEditFields?.length, 5); t.equal(appSchemaMap.Party.quickEditFields?.length, 5);
assert.strictEqual(regionalSchemaMap.Party.quickEditFields?.length, 8); t.equal(regionalSchemaMap.Party.quickEditFields?.length, 8);
}); t.end();
}); });
const regionalCombined = getRegionalCombinedSchemas( const regionalCombined = getRegionalCombinedSchemas(
appSchemaMap, appSchemaMap,
regionalSchemaMap regionalSchemaMap
); );
describe('Regional Combined Schemas', function () {
specify('Field Counts', function () {
assert.strictEqual(regionalCombined.Party.fields?.length, 11);
});
specify('Quick Edit Field Counts', function () { test('Field Counts', function (t) {
assert.strictEqual(regionalSchemaMap.Party.quickEditFields?.length, 8); t.equal(regionalCombined.Party.fields?.length, 11);
}); t.end();
});
specify('Schema Equality with App Schemas', function () { test('Quick Edit Field Counts', function (t) {
assert.strictEqual( t.equal(regionalSchemaMap.Party.quickEditFields?.length, 8);
isEqual(regionalCombined.Account, appSchemaMap.Account), t.end();
true });
);
assert.strictEqual( test('Schema Equality with App Schemas', function (t) {
t.equal(isEqual(regionalCombined.Account, appSchemaMap.Account), true);
t.equal(
isEqual(regionalCombined.JournalEntry, appSchemaMap.JournalEntry), isEqual(regionalCombined.JournalEntry, appSchemaMap.JournalEntry),
true true
); );
assert.strictEqual( t.equal(
isEqual( isEqual(
regionalCombined.JournalEntryAccount, regionalCombined.JournalEntryAccount,
appSchemaMap.JournalEntryAccount appSchemaMap.JournalEntryAccount
), ),
true true
); );
assert.strictEqual( t.equal(isEqual(regionalCombined.Customer, appSchemaMap.Customer), true);
isEqual(regionalCombined.Customer, appSchemaMap.Customer), t.equal(isEqual(regionalCombined.Party, appSchemaMap.Party), false);
true t.end();
); });
assert.strictEqual(
isEqual(regionalCombined.Party, appSchemaMap.Party),
false
);
});
});
const abstractCombined = cleanSchemas( const abstractCombined = cleanSchemas(
getAbstractCombinedSchemas(regionalCombined) getAbstractCombinedSchemas(regionalCombined)
); );
describe('Abstract Combined Schemas', function () {
specify('Meta Properties', function () {
assert.strictEqual(abstractCombined.Customer!.extends, undefined);
});
specify('Abstract Schema Existance', function () { test('Meta Properties', function (t) {
assert.strictEqual(abstractCombined.Party, undefined); t.equal(abstractCombined.Customer!.extends, undefined);
}); t.end();
});
specify('Field Counts', function () { test('Abstract Schema Existance', function (t) {
assert.strictEqual(abstractCombined.Customer!.fields?.length, 11); t.equal(abstractCombined.Party, undefined);
}); t.end();
});
specify('Quick Edit Field Counts', function () { test('Field Counts', function (t) {
assert.strictEqual(abstractCombined.Customer!.quickEditFields?.length, 8); t.equal(abstractCombined.Customer!.fields?.length, 11);
}); t.end();
});
specify('Schema Equality with App Schemas', function () { test('Quick Edit Field Counts', function (t) {
assert.strictEqual( t.equal(abstractCombined.Customer!.quickEditFields?.length, 8);
isEqual(abstractCombined.Account, appSchemaMap.Account), t.end();
true });
);
assert.strictEqual( test('Schema Equality with App Schemas', function (t) {
t.equal(isEqual(abstractCombined.Account, appSchemaMap.Account), true);
t.equal(
isEqual(abstractCombined.JournalEntry, appSchemaMap.JournalEntry), isEqual(abstractCombined.JournalEntry, appSchemaMap.JournalEntry),
true true
); );
assert.strictEqual( t.equal(
isEqual( isEqual(
abstractCombined.JournalEntryAccount, abstractCombined.JournalEntryAccount,
appSchemaMap.JournalEntryAccount appSchemaMap.JournalEntryAccount
), ),
true true
); );
assert.strictEqual( t.equal(isEqual(abstractCombined.Customer, appSchemaMap.Customer), false);
isEqual(abstractCombined.Customer, appSchemaMap.Customer), t.end();
false });
);
});
specify('Schema Field Existance', function () { test('Schema Field Existance', function (t) {
assert.strictEqual( t.equal(
everyFieldExists( everyFieldExists(
regionalSchemaMap.Party.quickEditFields ?? [], regionalSchemaMap.Party.quickEditFields ?? [],
abstractCombined.Customer! abstractCombined.Customer!
), ),
true true
); );
}); t.end();
}); });
let almostFinalSchemas = cloneDeep(abstractCombined); let almostFinalSchemas = cloneDeep(abstractCombined);
almostFinalSchemas = addMetaFields(almostFinalSchemas); almostFinalSchemas = addMetaFields(almostFinalSchemas);
const finalSchemas = setSchemaNameOnFields(almostFinalSchemas); const finalSchemas = setSchemaNameOnFields(almostFinalSchemas);
const metaSchemaMap = getMapFromList(metaSchemas, 'name'); const metaSchemaMap = getMapFromList(metaSchemas, 'name');
const baseFieldNames = metaSchemaMap.base.fields!.map((f) => f.fieldname); const baseFieldNames = metaSchemaMap.base.fields!.map((f) => f.fieldname);
const childFieldNames = metaSchemaMap.child.fields!.map((f) => f.fieldname); const childFieldNames = metaSchemaMap.child.fields!.map((f) => f.fieldname);
const treeFieldNames = metaSchemaMap.tree.fields!.map((f) => f.fieldname); const treeFieldNames = metaSchemaMap.tree.fields!.map((f) => f.fieldname);
const submittableFieldNames = metaSchemaMap.submittable.fields!.map( const submittableFieldNames = metaSchemaMap.submittable.fields!.map(
(f) => f.fieldname (f) => f.fieldname
); );
const allFieldNames = [ const allFieldNames = [
...baseFieldNames, ...baseFieldNames,
...childFieldNames, ...childFieldNames,
...treeFieldNames, ...treeFieldNames,
...submittableFieldNames, ...submittableFieldNames,
]; ];
describe('Final Schemas', function () { test('Schema Name Existsance', function (t) {
specify('Schema Name Existsance', function () {
for (const schemaName in finalSchemas) { for (const schemaName in finalSchemas) {
for (const field of finalSchemas[schemaName]?.fields!) { for (const field of finalSchemas[schemaName]?.fields!) {
assert.strictEqual(field.schemaName, schemaName); t.equal(field.schemaName, schemaName);
} }
} }
}); t.end();
});
specify('Schema Field Existance', function () { test('Schema Field Existance', function (t) {
assert.strictEqual( t.equal(everyFieldExists(baseFieldNames, finalSchemas.Customer!), true);
everyFieldExists(baseFieldNames, finalSchemas.Customer!),
true
);
assert.strictEqual( t.equal(
someFieldExists( someFieldExists(
subtract(allFieldNames, baseFieldNames), subtract(allFieldNames, baseFieldNames),
finalSchemas.Customer! finalSchemas.Customer!
@ -175,7 +163,7 @@ describe('Schema Builder', function () {
false false
); );
assert.strictEqual( t.equal(
everyFieldExists( everyFieldExists(
[...baseFieldNames, ...submittableFieldNames], [...baseFieldNames, ...submittableFieldNames],
finalSchemas.JournalEntry! finalSchemas.JournalEntry!
@ -183,7 +171,7 @@ describe('Schema Builder', function () {
true true
); );
assert.strictEqual( t.equal(
someFieldExists( someFieldExists(
subtract(allFieldNames, baseFieldNames, submittableFieldNames), subtract(allFieldNames, baseFieldNames, submittableFieldNames),
finalSchemas.JournalEntry! finalSchemas.JournalEntry!
@ -191,12 +179,12 @@ describe('Schema Builder', function () {
false false
); );
assert.strictEqual( t.equal(
everyFieldExists(childFieldNames, finalSchemas.JournalEntryAccount!), everyFieldExists(childFieldNames, finalSchemas.JournalEntryAccount!),
true true
); );
assert.strictEqual( t.equal(
someFieldExists( someFieldExists(
subtract(allFieldNames, childFieldNames), subtract(allFieldNames, childFieldNames),
finalSchemas.JournalEntryAccount! finalSchemas.JournalEntryAccount!
@ -204,7 +192,7 @@ describe('Schema Builder', function () {
false false
); );
assert.strictEqual( t.equal(
everyFieldExists( everyFieldExists(
[...treeFieldNames, ...baseFieldNames], [...treeFieldNames, ...baseFieldNames],
finalSchemas.Account! finalSchemas.Account!
@ -212,13 +200,13 @@ describe('Schema Builder', function () {
true true
); );
assert.strictEqual( t.equal(
someFieldExists( someFieldExists(
subtract(allFieldNames, treeFieldNames, baseFieldNames), subtract(allFieldNames, treeFieldNames, baseFieldNames),
finalSchemas.Account! finalSchemas.Account!
), ),
false false
); );
});
}); t.end();
}); });

View File

@ -1,4 +1,7 @@
import { DatabaseManager } from 'backend/database/manager';
import { config } from 'dotenv'; import { config } from 'dotenv';
import { Fyo } from 'fyo';
import { DummyAuthDemux } from 'fyo/tests/helpers';
import { SetupWizardOptions } from 'src/setup/types'; import { SetupWizardOptions } from 'src/setup/types';
import { getFiscalYear } from 'utils/misc'; import { getFiscalYear } from 'utils/misc';
@ -21,3 +24,12 @@ export function getTestDbPath(dbPath?: string) {
config(); config();
return dbPath ?? process.env.TEST_DB_PATH ?? ':memory:'; return dbPath ?? process.env.TEST_DB_PATH ?? ':memory:';
} }
export function getTestFyo(): Fyo {
return new Fyo({
DatabaseDemux: DatabaseManager,
AuthDemux: DummyAuthDemux,
isTest: true,
isElectron: false,
});
}

View File

@ -1,40 +1,25 @@
import * as assert from 'assert';
import { DatabaseManager } from 'backend/database/manager';
import { assertDoesNotThrow } from 'backend/database/tests/helpers'; import { assertDoesNotThrow } from 'backend/database/tests/helpers';
import { Fyo } from 'fyo';
import { DummyAuthDemux } from 'fyo/tests/helpers';
import 'mocha';
import setupInstance from 'src/setup/setupInstance'; import setupInstance from 'src/setup/setupInstance';
import { SetupWizardOptions } from 'src/setup/types'; import { SetupWizardOptions } from 'src/setup/types';
import test from 'tape';
import { getValueMapFromList } from 'utils'; import { getValueMapFromList } from 'utils';
import { getTestDbPath, getTestSetupWizardOptions } from './helpers'; import {
getTestDbPath,
getTestFyo,
getTestSetupWizardOptions
} from './helpers';
describe('setupInstance', function () { const dbPath = getTestDbPath();
const dbPath = getTestDbPath(); const setupOptions = getTestSetupWizardOptions();
const setupOptions = getTestSetupWizardOptions(); const fyo = getTestFyo();
let fyo: Fyo; test('setupInstance', async () => {
this.beforeAll(function () {
fyo = new Fyo({
DatabaseDemux: DatabaseManager,
AuthDemux: DummyAuthDemux,
isTest: true,
isElectron: false,
});
});
this.afterAll(async function () {
await fyo.close();
});
specify('setupInstance', async function () {
await assertDoesNotThrow(async () => { await assertDoesNotThrow(async () => {
await setupInstance(dbPath, setupOptions, fyo); await setupInstance(dbPath, setupOptions, fyo);
}, 'setup instance failed'); }, 'setup instance failed');
}); });
specify('check setup Singles', async function () { test('check setup Singles', async (t) => {
const setupFields = [ const setupFields = [
'companyName', 'companyName',
'country', 'country',
@ -57,22 +42,25 @@ describe('setupInstance', function () {
dbValue = dbValue.toISOString().split('T')[0]; dbValue = dbValue.toISOString().split('T')[0];
} }
assert.strictEqual( t.equal(
dbValue as string, dbValue as string,
optionsValue, optionsValue,
`${field} mismatch (${dbValue},${optionsValue})` `${field}: (${dbValue}, ${optionsValue})`
); );
} }
}); });
specify('check null singles', async function () { test('check null singles', async (t) => {
const nullFields = ['gstin', 'logo', 'phone', 'address']; const nullFields = ['gstin', 'logo', 'phone', 'address'];
const nullSingles = await fyo.db.getSingleValues(...nullFields); const nullSingles = await fyo.db.getSingleValues(...nullFields);
assert.strictEqual( t.equal(
nullSingles.length, nullSingles.length,
0, 0,
`null singles found ${JSON.stringify(nullSingles)}` `null singles: ${JSON.stringify(nullSingles)}`
); );
}); });
test.onFinish(async () => {
await fyo.close();
}); });

767
yarn.lock

File diff suppressed because it is too large Load Diff