ZenVoich / mops

Package manager for the Motoko programming language
https://mops.one
MIT License
35 stars 3 forks source link

Any way to set the caller in mops test? #188

Closed william-iclight closed 7 months ago

william-iclight commented 7 months ago

Hi guys, I want to use custom users call my test canister. But I do not know how to set different accounts. This example show I can create an agent:

import Debug "mo:base/Debug";

actor class MyCanister() {
    public query ({caller}) func getCaller() : async Principal {
        caller;
    };
};

actor class Agent(canister : MyCanister) {
    public func call() : async Principal {
        await canister.getCaller();
    };
};

let myCanister = await MyCanister();
let agent1 = await Agent(myCanister);
let agent2 = await Agent(myCanister);

Debug.print(debug_show(await agent1.call()));
Debug.print(debug_show(await agent2.call()));

But it seems the callers will be a canister not a user. At the same time I have to implement all the target functions in the agent. So any way to set the caller in mops test?

ZenVoich commented 7 months ago

Hi @william-iclight !

But I do not know how to set different accounts.

When you create the Agent canister it will obtain new principal id. So agent1 and agent2 have different principals(you can treat them as a users).

But it seems the callers will be a canister not a user

This is ok, because caller type is Principal for both a user and a canister. Only difference is the length of principal(shorter for canisters). If you have no checks for principal size there will be no difference.

At the same time I have to implement all the target functions in the agent.

Yes, I haven't figured out how to avoid this.

Probably it will be easier to write canister tests in JavaScript(or python/rust) using pocket-ic library https://forum.dfinity.org/t/announcing-picjs-typescript-javascript-support-for-pocketic/24479

Example https://github.com/hadronous/pic-js/blob/main/examples/todo/tests/src/todo.spec.ts

And use mops only to run unit tests in Motoko.

So any way to set the caller in mops test?

There is no way to set arbitrary caller in Motoko, we can only obtain next canister id by creating actor class.