Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: logs with serverless functions #1209

Merged
merged 2 commits into from
Feb 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/tests/fixtures/test_satellite/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ crate-type = ["cdylib"]
[dependencies]
candid.workspace = true
ic-cdk.workspace = true
junobuild-satellite = { path = "../../../libs/satellite", default-features = false, features = ["on_set_doc"] }
junobuild-satellite = { path = "../../../libs/satellite", default-features = false, features = ["on_set_doc", "on_delete_doc"] }
junobuild-macros = { path = "../../../libs/macros" }
13 changes: 11 additions & 2 deletions src/tests/fixtures/test_satellite/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
use junobuild_macros::on_set_doc;
use junobuild_satellite::{include_satellite, OnSetDocContext};
use junobuild_macros::{on_set_doc, on_delete_doc};
use junobuild_satellite::{include_satellite, info, error, OnSetDocContext, OnDeleteDocContext};

#[on_set_doc]
fn on_set_doc(_context: OnSetDocContext) -> Result<(), String> {
info("Hello world".to_string())?;

Ok(())
}

#[on_delete_doc]
fn on_delete_doc(_context: OnDeleteDocContext) -> Result<(), String> {
error("Delete Hello world".to_string())?;

Ok(())
}

Expand Down
14 changes: 14 additions & 0 deletions src/tests/specs/mocks/collection.mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { SetRule } from '$declarations/satellite/satellite.did';
import { toNullable } from '@dfinity/utils';

export const mockSetRule: SetRule = {
memory: toNullable({ Heap: null }),
max_size: toNullable(),
max_capacity: toNullable(),
read: { Managed: null },
mutable_permissions: toNullable(),
write: { Managed: null },
version: toNullable(),
rate_config: toNullable(),
max_changes_per_user: toNullable()
};
9 changes: 9 additions & 0 deletions src/tests/specs/mocks/list.mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { ListParams } from '$declarations/satellite/satellite.did';
import { toNullable } from '@dfinity/utils';

export const mockListParams: ListParams = {
matcher: toNullable(),
order: toNullable(),
owner: toNullable(),
paginate: toNullable()
};
156 changes: 156 additions & 0 deletions src/tests/specs/satellite.logs.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import type { _SERVICE as TestSatelliteActor } from '$test-declarations/test_satellite/test_satellite.did';
import { idlFactory as idlTestFactorySatellite } from '$test-declarations/test_satellite/test_satellite.factory.did';
import { Ed25519KeyIdentity } from '@dfinity/identity';
import { toNullable } from '@dfinity/utils';
import { type Actor, PocketIc } from '@hadronous/pic';
import { fromArray } from '@junobuild/utils';
import { afterAll, beforeAll, describe, expect, inject } from 'vitest';
import { mockSetRule } from './mocks/collection.mocks';
import { mockListParams } from './mocks/list.mocks';
import { tick } from './utils/pic-tests.utils';
import { createDoc as createDocUtils } from './utils/satellite-doc-tests.utils';
import { controllersInitArgs, TEST_SATELLITE_WASM_PATH } from './utils/setup-tests.utils';

describe('Satellite Logging', () => {
let pic: PocketIc;
let actor: Actor<TestSatelliteActor>;

const controller = Ed25519KeyIdentity.generate();

const TEST_COLLECTION = 'test_logging';

beforeAll(async () => {
pic = await PocketIc.create(inject('PIC_URL'));

const { actor: c, canisterId } = await pic.setupCanister<TestSatelliteActor>({
idlFactory: idlTestFactorySatellite,
wasm: TEST_SATELLITE_WASM_PATH,
arg: controllersInitArgs(controller),
sender: controller.getPrincipal()
});

actor = c;
actor.setIdentity(controller);

await tick(pic);

// The random number generator is only initialized on upgrade because dev that do not use serverless functions do not need it
await pic.upgradeCanister({
canisterId,
wasm: TEST_SATELLITE_WASM_PATH,
sender: controller.getPrincipal()
});

// Wait for post_upgrade to kicks in since we defer instantiation of random
await tick(pic);

const { set_rule } = actor;
await set_rule({ Db: null }, TEST_COLLECTION, mockSetRule);
});

afterAll(async () => {
await pic?.tearDown();
});

const waitServerlessFunction = async () => {
// Wait for the serverless function to being fired
await tick(pic);
};

const createDoc = async (): Promise<string> => {
return createDocUtils({
actor,
collection: TEST_COLLECTION
});
};

it('should log an info when on_set_doc hook is fired', async () => {
await createDoc();

await waitServerlessFunction();

const { list_docs } = actor;

const { items: logs } = await list_docs('#log', mockListParams);

expect(logs).toHaveLength(1);

const [log, _] = logs;
const [__, doc] = log;

const data = await fromArray(doc.data);

expect(data).toEqual({
data: null,
level: 'Info',
message: 'Hello world'
});
});

it('should log an error when on_delete_doc hook is fired', async () => {
const { list_docs, del_doc } = actor;

const { items } = await list_docs(TEST_COLLECTION, mockListParams);

const [item] = items;
const [key, doc] = item;

await del_doc(TEST_COLLECTION, key, doc);

await waitServerlessFunction();

const { items: logs } = await list_docs('#log', {
...mockListParams,
order: toNullable({
desc: true,
field: { CreatedAt: null }
})
});

expect(logs).toHaveLength(2);

const [log, _] = logs;
const [__, docLog] = log;

const data = await fromArray(docLog.data);

expect(data).toEqual({
data: null,
level: 'Error',
message: 'Delete Hello world'
});
});

it('should create logs with different random keys', async () => {
await Promise.all(Array.from({ length: 10 }).map(createDoc));

await waitServerlessFunction();

const { list_docs } = actor;

const { items: logs } = await list_docs('#log', mockListParams);

expect(logs).toHaveLength(12);

const keys = new Set([...logs.map(([key, _]) => key)]);
expect(keys).toHaveLength(12);

// Log key is format!("{}-{}", time(), nonce)
// When we create doc and log with serverless without tick, the time should be the same
// Therefore, without nonce, the count of entry should be smaller than the effective count of time we logged
const trimmedKey = new Set([...logs.map(([key, _]) => key.split('-')[0])]);
expect(trimmedKey.size).toBeLessThan(12);
});

it('should limit log entries to hundred', async () => {
await Promise.all(Array.from({ length: 101 }).map(createDoc));

await waitServerlessFunction();

const { list_docs } = actor;

const { items: logs } = await list_docs('#log', mockListParams);

expect(logs).toHaveLength(100);
});
});
6 changes: 6 additions & 0 deletions src/tests/specs/utils/setup-tests.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ export const OBSERVATORY_WASM_PATH = existsSync(OBSERVATORY_WASM_PATH_CI)
? OBSERVATORY_WASM_PATH_CI
: OBSERVATORY_WASM_PATH_LOCAL;

const TEST_SATELLITE_WASM_PATH_LOCAL = join(WASM_PATH_LOCAL, 'test_satellite.wasm.gz');
const TEST_SATELLITE_WASM_PATH_CI = join(process.cwd(), 'test_satellite.wasm.gz');
export const TEST_SATELLITE_WASM_PATH = existsSync(SATELLITE_WASM_PATH_CI)
? TEST_SATELLITE_WASM_PATH_CI
: TEST_SATELLITE_WASM_PATH_LOCAL;

export const controllersInitArgs = (controllers: Identity | Principal[]): ArrayBuffer =>
IDL.encode(
[
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
"extends": "./tsconfig.json",
"compilerOptions": {
"paths": {
"$test-declarations": ["./src/tests/declarations"],
"$test-declarations/*": ["./src/tests/declarations/*"],
"$declarations": ["./src/declarations"],
"$declarations/*": ["./src/declarations/*"],
"$lib": ["./src/frontend/src/lib"],
Expand Down
4 changes: 4 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ export default defineConfig({
},
resolve: {
alias: [
{
find: '$test-declarations',
replacement: resolve(__dirname, 'src/tests/declarations')
},
{
find: '$declarations',
replacement: resolve(__dirname, 'src/declarations')
Expand Down