added event related tests to mutator, fixed tests

This commit is contained in:
dswbx
2025-01-16 10:11:10 +01:00
parent 6c9707d12c
commit aa4aca1a90
13 changed files with 89 additions and 32 deletions

View File

@@ -1,11 +1,5 @@
import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test"; import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test";
import { import { Event, EventManager, InvalidEventReturn, NoParamEvent } from "../../src/core/events";
Event,
EventManager,
InvalidEventReturn,
type ListenerHandler,
NoParamEvent
} from "../../src/core/events";
import { disableConsoleLog, enableConsoleLog } from "../helper"; import { disableConsoleLog, enableConsoleLog } from "../helper";
beforeAll(disableConsoleLog); beforeAll(disableConsoleLog);

View File

@@ -10,6 +10,7 @@ import {
RelationMutator, RelationMutator,
TextField TextField
} from "../../../src/data"; } from "../../../src/data";
import * as proto from "../../../src/data/prototype";
import { getDummyConnection } from "../helper"; import { getDummyConnection } from "../helper";
const { dummyConnection, afterAllCleanup } = getDummyConnection(); const { dummyConnection, afterAllCleanup } = getDummyConnection();
@@ -83,14 +84,12 @@ describe("[data] Mutator (ManyToOne)", async () => {
// persisting reference should ... // persisting reference should ...
expect( expect(
postRelMutator.persistReference(relations[0], "users", { postRelMutator.persistReference(relations[0]!, "users", {
$set: { id: userData.data.id } $set: { id: userData.data.id }
}) })
).resolves.toEqual(["users_id", userData.data.id]); ).resolves.toEqual(["users_id", userData.data.id]);
// @todo: add what methods are allowed to relation, like $create should not be allowed for post<>users // @todo: add what methods are allowed to relation, like $create should not be allowed for post<>users
process.exit(0);
const userRelMutator = new RelationMutator(users, em); const userRelMutator = new RelationMutator(users, em);
expect(userRelMutator.getRelationalKeys()).toEqual(["posts"]); expect(userRelMutator.getRelationalKeys()).toEqual(["posts"]);
}); });
@@ -99,7 +98,7 @@ describe("[data] Mutator (ManyToOne)", async () => {
expect( expect(
em.mutator(posts).insertOne({ em.mutator(posts).insertOne({
title: "post1", title: "post1",
users_id: 1 // user does not exist yet users_id: 100 // user does not exist yet
}) })
).rejects.toThrow(); ).rejects.toThrow();
}); });
@@ -299,4 +298,71 @@ describe("[data] Mutator (Events)", async () => {
expect(events.has(MutatorEvents.MutatorDeleteBefore.slug)).toBeTrue(); expect(events.has(MutatorEvents.MutatorDeleteBefore.slug)).toBeTrue();
expect(events.has(MutatorEvents.MutatorDeleteAfter.slug)).toBeTrue(); expect(events.has(MutatorEvents.MutatorDeleteAfter.slug)).toBeTrue();
}); });
/*test("insertOne event return is respected", async () => {
const posts = proto.entity("posts", {
title: proto.text(),
views: proto.number()
});
const conn = getDummyConnection();
const em = new EntityManager([posts], conn.dummyConnection);
await em.schema().sync({ force: true });
const emgr = em.emgr as EventManager<any>;
emgr.onEvent(
// @ts-ignore
EntityManager.Events.MutatorInsertBefore,
async (event) => {
return {
...event.params.data,
views: 2
};
},
"sync"
);
const mutator = em.mutator("posts");
const result = await mutator.insertOne({ title: "test", views: 1 });
expect(result.data).toEqual({
id: 1,
title: "test",
views: 2
});
});
test("updateOne event return is respected", async () => {
const posts = proto.entity("posts", {
title: proto.text(),
views: proto.number()
});
const conn = getDummyConnection();
const em = new EntityManager([posts], conn.dummyConnection);
await em.schema().sync({ force: true });
const emgr = em.emgr as EventManager<any>;
emgr.onEvent(
// @ts-ignore
EntityManager.Events.MutatorUpdateBefore,
async (event) => {
return {
...event.params.data,
views: event.params.data.views + 1
};
},
"sync"
);
const mutator = em.mutator("posts");
const created = await mutator.insertOne({ title: "test", views: 1 });
const result = await mutator.updateOne(created.data.id, { views: 2 });
expect(result.data).toEqual({
id: 1,
title: "test",
views: 3
});
});*/
}); });

View File

@@ -1,7 +1,6 @@
import { afterAll, describe, expect, test } from "bun:test"; import { afterAll, describe, expect, test } from "bun:test";
// @ts-ignore
import { Perf } from "@bknd/core/utils";
import type { Kysely, Transaction } from "kysely"; import type { Kysely, Transaction } from "kysely";
import { Perf } from "../../../src/core/utils";
import { import {
Entity, Entity,
EntityManager, EntityManager,
@@ -24,7 +23,7 @@ async function sleep(ms: number) {
} }
describe("[Repository]", async () => { describe("[Repository]", async () => {
test("bulk", async () => { test.skip("bulk", async () => {
//const connection = dummyConnection; //const connection = dummyConnection;
//const connection = getLocalLibsqlConnection(); //const connection = getLocalLibsqlConnection();
const credentials = null as any; // @todo: determine what to do here const credentials = null as any; // @todo: determine what to do here

View File

@@ -36,7 +36,7 @@ describe("[data] WithBuilder", async () => {
const res = qb.compile(); const res = qb.compile();
expect(res.sql).toBe( expect(res.sql).toBe(
'select (select coalesce(json_group_array(json_object(\'id\', "agg"."id", \'content\', "agg"."content", \'author_id\', "agg"."author_id")), \'[]\') from (select "posts"."id" as "id", "posts"."content" as "content", "posts"."author_id" as "author_id" from "posts" where "users"."id" = "posts"."author_id" limit ?) as agg) as "posts" from "users"' 'select (select coalesce(json_group_array(json_object(\'id\', "agg"."id", \'content\', "agg"."content", \'author_id\', "agg"."author_id")), \'[]\') from (select "posts"."id" as "id", "posts"."content" as "content", "posts"."author_id" as "author_id" from "posts" as "posts" where "posts"."author_id" = "users"."id" limit ?) as agg) as "posts" from "users"'
); );
expect(res.parameters).toEqual([5]); expect(res.parameters).toEqual([5]);
@@ -50,7 +50,7 @@ describe("[data] WithBuilder", async () => {
const res2 = qb2.compile(); const res2 = qb2.compile();
expect(res2.sql).toBe( expect(res2.sql).toBe(
'select (select json_object(\'id\', "obj"."id", \'username\', "obj"."username") from (select "users"."id" as "id", "users"."username" as "username" from "users" where "posts"."author_id" = "users"."id" limit ?) as obj) as "author" from "posts"' 'select (select json_object(\'id\', "obj"."id", \'username\', "obj"."username") from (select "author"."id" as "id", "author"."username" as "username" from "users" as "author" where "author"."id" = "posts"."author_id" limit ?) as obj) as "author" from "posts"'
); );
expect(res2.parameters).toEqual([1]); expect(res2.parameters).toEqual([1]);
}); });

View File

@@ -13,10 +13,6 @@ describe("[data] EnumField", async () => {
{ options: options(["a", "b", "c"]) } { options: options(["a", "b", "c"]) }
); );
test("yields if no options", async () => {
expect(() => new EnumField("test", { options: options([]) })).toThrow();
});
test("yields if default value is not a valid option", async () => { test("yields if default value is not a valid option", async () => {
expect( expect(
() => new EnumField("test", { options: options(["a", "b"]), default_value: "c" }) () => new EnumField("test", { options: options(["a", "b"]), default_value: "c" })

View File

@@ -15,11 +15,9 @@ describe("[data] Field", async () => {
runBaseFieldTests(FieldSpec, { defaultValue: "test", schemaType: "text" }); runBaseFieldTests(FieldSpec, { defaultValue: "test", schemaType: "text" });
test.only("default config", async () => { test("default config", async () => {
const field = new FieldSpec("test");
const config = Default(baseFieldConfigSchema, {}); const config = Default(baseFieldConfigSchema, {});
expect(stripMark(new FieldSpec("test").config)).toEqual(config); expect(stripMark(new FieldSpec("test").config)).toEqual(config);
console.log("config", new TextField("test", { required: true }).toJSON());
}); });
test("transformPersist (specific)", async () => { test("transformPersist (specific)", async () => {

View File

@@ -32,7 +32,7 @@ describe("[data] JsonField", async () => {
}); });
test("getValue", async () => { test("getValue", async () => {
expect(field.getValue({ test: 1 }, "form")).toBe('{"test":1}'); expect(field.getValue({ test: 1 }, "form")).toBe('{\n "test": 1\n}');
expect(field.getValue("string", "form")).toBe('"string"'); expect(field.getValue("string", "form")).toBe('"string"');
expect(field.getValue(1, "form")).toBe("1"); expect(field.getValue(1, "form")).toBe("1");

View File

@@ -70,9 +70,9 @@ describe("[data] EntityRelation", async () => {
it("required", async () => { it("required", async () => {
const relation1 = new TestEntityRelation(); const relation1 = new TestEntityRelation();
expect(relation1.config.required).toBe(false); expect(relation1.required).toBe(false);
const relation2 = new TestEntityRelation({ required: true }); const relation2 = new TestEntityRelation({ required: true });
expect(relation2.config.required).toBe(true); expect(relation2.required).toBe(true);
}); });
}); });

View File

@@ -3,7 +3,7 @@ import { randomString } from "../../../src/core/utils";
import { StorageCloudinaryAdapter } from "../../../src/media"; import { StorageCloudinaryAdapter } from "../../../src/media";
import { config } from "dotenv"; import { config } from "dotenv";
const dotenvOutput = config({ path: `${import.meta.dir}/../../.env` }); const dotenvOutput = config({ path: `${import.meta.dir}/../../../.env` });
const { const {
CLOUDINARY_CLOUD_NAME, CLOUDINARY_CLOUD_NAME,
CLOUDINARY_API_KEY, CLOUDINARY_API_KEY,

View File

@@ -15,7 +15,7 @@ describe("StorageLocalAdapter", () => {
test("puts an object", async () => { test("puts an object", async () => {
objects = (await adapter.listObjects()).length; objects = (await adapter.listObjects()).length;
expect(await adapter.putObject(filename, await file.arrayBuffer())).toBeString(); expect(await adapter.putObject(filename, file)).toBeString();
}); });
test("lists objects", async () => { test("lists objects", async () => {

View File

@@ -3,14 +3,14 @@ import { randomString } from "../../../src/core/utils";
import { StorageS3Adapter } from "../../../src/media"; import { StorageS3Adapter } from "../../../src/media";
import { config } from "dotenv"; import { config } from "dotenv";
const dotenvOutput = config({ path: `${import.meta.dir}/../../.env` }); const dotenvOutput = config({ path: `${import.meta.dir}/../../../.env` });
const { R2_ACCESS_KEY, R2_SECRET_ACCESS_KEY, R2_URL, AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_S3_URL } = const { R2_ACCESS_KEY, R2_SECRET_ACCESS_KEY, R2_URL, AWS_ACCESS_KEY, AWS_SECRET_KEY, AWS_S3_URL } =
dotenvOutput.parsed!; dotenvOutput.parsed!;
// @todo: mock r2/s3 responses for faster tests // @todo: mock r2/s3 responses for faster tests
const ALL_TESTS = process.env.ALL_TESTS; const ALL_TESTS = !!process.env.ALL_TESTS;
describe("Storage", async () => { describe.skipIf(ALL_TESTS)("StorageS3Adapter", async () => {
console.log("ALL_TESTS", process.env.ALL_TESTS); console.log("ALL_TESTS", process.env.ALL_TESTS);
const versions = [ const versions = [
[ [

View File

@@ -1,2 +1,5 @@
[install] [install]
registry = "http://localhost:4873" #registry = "http://localhost:4873"
[test]
coverageSkipTestFiles = true

View File

@@ -7,6 +7,7 @@
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"test": "ALL_TESTS=1 bun test --bail", "test": "ALL_TESTS=1 bun test --bail",
"test:coverage": "ALL_TESTS=1 bun test --bail --coverage",
"build": "NODE_ENV=production bun run build.ts --minify --types", "build": "NODE_ENV=production bun run build.ts --minify --types",
"build:all": "rm -rf dist && bun run build:static && NODE_ENV=production bun run build.ts --minify --types --clean && bun run build:cli", "build:all": "rm -rf dist && bun run build:static && NODE_ENV=production bun run build.ts --minify --types --clean && bun run build:cli",
"build:cli": "bun build src/cli/index.ts --target node --outdir dist/cli --minify", "build:cli": "bun build src/cli/index.ts --target node --outdir dist/cli --minify",