在基板运行时中使用时间戳:set_timestamp找不到



我正在尝试快进时间以对自定义运行时模块进行一些测试。我已经查看了此线程的答案并按照答案使用时间戳,但是,我无法访问set_timestamp方法。

设置:

#[cfg(test)]
mod tests {
use super::*;
use support::dispatch::Vec;
use runtime_primitives::traits::{Hash};
use runtime_io::with_externalities;
use primitives::{H256, Blake2Hasher};
use timestamp;
use support::{impl_outer_origin, assert_ok, assert_noop};
use runtime_primitives::{
BuildStorage,
traits::{BlakeTwo256, IdentityLookup},
testing::{Digest, DigestItem, Header}
};
impl_outer_origin! {
pub enum Origin for Test {}
}
#[derive(Clone, Eq, PartialEq)]
pub struct Test;
impl system::Trait for Test {
type Origin = Origin;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type Digest = Digest;
type AccountId = u64;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type Log = DigestItem;
}
impl super::Trait for Test {
type Event = ();
}
impl timestamp::Trait for Test {
type Moment = u64;
type OnTimestampSet = ();
}
type Pizza = Module<Test>;

错误如下:

error[E0599]: no function or associated item named `set_timestamp` found for type 
`srml_timestamp::Module<tests::Test>` in the current scope

|
254 |  let now = <timestamp::Module<tests::Test>>::set_timestamp(9);
|                                              ^^^^^^^^^^^^^ function or associated item 
not found in `srml_timestamp::Module<tests::Test>`

在 Substrate v1.0 中,set_timestamp函数具有#[cfg(feature = "std")]属性:

https://github.com/paritytech/substrate/blob/v1.0/srml/timestamp/src/lib.rs#L276

这意味着它仅在您使用std进行编译时才可见。当您编写测试时,这应该有效,但是我认为出现此问题是因为您尝试从运行时环境中调用它,这很no_std

如果由于某种原因您确实需要从运行时中修改时间戳,您应该能够直接这样做:

https://github.com/paritytech/substrate/blob/v1.0/srml/timestamp/src/lib.rs#L249

<timestamp::Module<T>>::Now::put(new_time)

(我还没有测试过这个,但类似的东西应该可以工作(。

让我知道这是否有帮助。

在 Substrate v1.0 中,你可以声明

type Moment = timestamp::Module<Test>;

然后使用它来设置特定的时间戳。

Moment::set_timestamp(9);

如果要获取时间戳值,可以执行以下操作:

let now_timestamp = Moment::now();

最新更新