blockchainmoveaptos

"Failed to borrow global resource" error while trying to get timestamp


I got a problem while writing an unit test for my module, and I realize that I can't get timestamp in unit test. I tried to get timestamp in the below code,

 #[test]
    fun get_seconds() {
        timestamp::now_seconds();
    }

It resulted this error

**$ sudo aptos move test --package-dir sources **
INCLUDING DEPENDENCY AptosFramework
INCLUDING DEPENDENCY AptosStdlib
INCLUDING DEPENDENCY MoveStdlib
BUILDING brkt
Running Move unit tests
[ FAIL    ] 0x7a3b3a0d212571b010a28b61d8cc5ff002faf4c617dfdd4f5187e10f8714d006::competition::get_seconds

Test failures:

Failures in 0x7a3b3a0d212571b010a28b61d8cc5ff002faf4c617dfdd4f5187e10f8714d006::competition:

┌── get_seconds ──────
│ error[E11001]: test failure
│    ┌─ /root/.move/https___github_com_aptos-labs_aptos-core_git_mainnet/aptos-move/framework/aptos-framework/sources/timestamp.move:62:9
│    │
│ 61 │     public fun now_microseconds(): u64 acquires CurrentTimeMicroseconds {
│    │                ---------------- In this function in 0x1::timestamp
│ 62 │         borrow_global<CurrentTimeMicroseconds>(@aptos_framework).microseconds
│    │         ^^^^^^^^^^^^^ Test was not expected to error, but it gave a MISSING_DATA (code 4008) error with error message: "Failed to borrow global resource from 0000000000000000000000000000000000000000000000000000000000000001". Error originating in the module 0000000000000000000000000000000000000000000000000000000000000001::timestamp rooted here
│ 
│ 
│ stack trace
│   timestamp::now_seconds(/root/.move/https___github_com_aptos-labs_aptos-core_git_mainnet/aptos-move/framework/aptos-framework/sources/timestamp.move:68)
│   competition::get_seconds(sources/base/competition.move:649)
│ 
└──────────────────

Test result: FAILED. Total tests: 1; passed: 0; failed: 1
{
  "Error": "Move unit tests failed"
}

Does anyone know about this error, or I really can't get timestamp in an unit test?


Solution

  • Testing uses different time instances than runtime. You should use things like this:

    clock::create_for_testing(ctx);
    
    test.take_shared<Clock>();