本体函数Unit testing模拟用户和组

注意:以下翻译的准确性尚未经过验证。这是使用 AIP ↗ 从原始英文文本进行的机器翻译。

模拟用户和组

用户模拟

您可以使用 createUser 创建用户的部分模拟,其中除了 idusername 之外的所有属性都是非必填的。您需要从 "@foundry/functions-testing-lib" 导入 { createUser }

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import { MyFunctions } from ".." import { verifyOntologyEditFunction, createGroup, createUser } from "@foundry/functions-testing-lib"; describe("example test suite", () => { const myFunctions = new MyFunctions(); test("test users and groups", async () => { // 创建一个组 const group = createGroup({ id: "groupId", }); // 创建一个用户 const user = createUser({ id: "userId", username: "username", }); // 期望函数 searchUsers 返回一个包含用户和组的数组 await expect(myFunctions.searchUsers("userId", "groupId")).resolves.toEqual([user, group]); }); });

这可以被用于在测试以下函数:

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 import { Function, OntologyEditFunction, Users, Group, Principal } from "@foundry/functions-api"; export class MyFunctions { @Function() public async searchUsers(userId: string, groupId: string): Promise<Principal[]> { // 获取用户和组的Principal对象 const existingPrincipals = await Promise.all([ Users.getUserByIdAsync(userId), // 异步获取用户ID对应的Principal Users.getGroupByIdAsync(groupId), // 异步获取组ID对应的Principal ]); // 过滤掉null或undefined的结果,并返回非空的Principal数组 return existingPrincipals.filter(r => !!r).map(r => r!); } }

分组模拟

您还可以使用 createGroup 创建一个部分分组模拟,其中除了 id 之外的所有属性都是非必填的。您需要从 "@foundry/functions-testing-lib" 导入 { createGroup }

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { MyFunctions } from ".." import { verifyOntologyEditFunction, createGroup } from "@foundry/functions-testing-lib"; describe("example test suite", () => { const myFunctions = new MyFunctions(); test("test groups", async () => { // 创建一个组对象,id为"groupId" const group = createGroup({ id: "groupId", }); // 期望myFunctions.searchGroups("groupId")异步解析后与[group]相等 await expect(myFunctions.searchGroups("groupId")).resolves.toEqual([group]); }); });
Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 import { Function, OntologyEditFunction, Users, Group, Principal } from "@foundry/functions-api"; export class MyFunctions { @Function() public async searchGroups(groupId: string): Promise<Principal[]> { // 使用 Promise.all 异步获取群组信息 const existingPrincipals = await Promise.all([ Users.getGroupByIdAsync(groupId), // 根据 groupId 异步获取群组信息 ]); // 过滤掉可能的空值并返回 Principal 数组 return existingPrincipals.filter(r => !!r).map(r => r!); } }