mock.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. #![cfg(test)]
  2. use frame_support::storage::StorageMap;
  3. use frame_support::traits::{OnFinalize, OnInitialize};
  4. use frame_support::{impl_outer_event, impl_outer_origin, parameter_types};
  5. use sp_core::H256;
  6. use sp_runtime::{
  7. testing::Header,
  8. traits::{BlakeTwo256, IdentityLookup},
  9. Perbill,
  10. };
  11. use crate::data_directory::ContentIdExists;
  12. pub use crate::data_directory::Voucher;
  13. pub use crate::data_directory::{ContentParameters, StorageObjectOwner};
  14. use crate::data_object_type_registry::IsActiveDataObjectType;
  15. use crate::ContentId;
  16. pub use crate::StorageWorkingGroupInstance;
  17. pub use crate::{data_directory, data_object_storage_registry, data_object_type_registry};
  18. use common::currency::GovernanceCurrency;
  19. use frame_support::StorageValue;
  20. use membership;
  21. pub use crate::data_directory::{
  22. DEFAULT_GLOBAL_VOUCHER, DEFAULT_UPLOADING_BLOCKED_STATUS, DEFAULT_VOUCHER,
  23. DEFAULT_VOUCHER_OBJECTS_LIMIT_UPPER_BOUND, DEFAULT_VOUCHER_SIZE_LIMIT_UPPER_BOUND,
  24. };
  25. mod working_group_mod {
  26. pub use super::StorageWorkingGroupInstance;
  27. pub use working_group::Event;
  28. }
  29. mod members {
  30. pub use membership::Event;
  31. }
  32. impl_outer_origin! {
  33. pub enum Origin for Test {}
  34. }
  35. impl_outer_event! {
  36. pub enum MetaEvent for Test {
  37. data_object_type_registry<T>,
  38. data_directory<T>,
  39. data_object_storage_registry<T>,
  40. balances<T>,
  41. members<T>,
  42. working_group_mod StorageWorkingGroupInstance <T>,
  43. frame_system<T>,
  44. }
  45. }
  46. pub const DEFAULT_LEADER_ACCOUNT_ID: u64 = 1;
  47. pub const DEFAULT_LEADER_MEMBER_ID: u64 = 1;
  48. pub const DEFAULT_LEADER_WORKER_ID: u32 = 1;
  49. pub struct SetLeadFixture;
  50. impl SetLeadFixture {
  51. pub fn set_default_lead() {
  52. let worker = working_group::Worker {
  53. member_id: DEFAULT_LEADER_MEMBER_ID,
  54. role_account_id: DEFAULT_LEADER_ACCOUNT_ID,
  55. reward_relationship: None,
  56. role_stake_profile: None,
  57. };
  58. // Create the worker.
  59. <working_group::WorkerById<Test, StorageWorkingGroupInstance>>::insert(
  60. DEFAULT_LEADER_WORKER_ID,
  61. worker,
  62. );
  63. // Update current lead.
  64. <working_group::CurrentLead<Test, StorageWorkingGroupInstance>>::put(
  65. DEFAULT_LEADER_WORKER_ID,
  66. );
  67. }
  68. }
  69. pub const TEST_FIRST_DATA_OBJECT_TYPE_ID: u64 = 1000;
  70. pub const TEST_FIRST_CONTENT_ID: u64 = 2000;
  71. pub const TEST_FIRST_RELATIONSHIP_ID: u64 = 3000;
  72. pub const TEST_FIRST_METADATA_ID: u64 = 4000;
  73. pub const TEST_MOCK_LIAISON_STORAGE_PROVIDER_ID: u32 = 1;
  74. pub const TEST_MOCK_EXISTING_CID: u64 = 42;
  75. pub struct AnyDataObjectTypeIsActive {}
  76. impl<T: data_object_type_registry::Trait> IsActiveDataObjectType<T> for AnyDataObjectTypeIsActive {
  77. fn is_active_data_object_type(_which: &T::DataObjectTypeId) -> bool {
  78. true
  79. }
  80. }
  81. pub struct MockContent {}
  82. impl ContentIdExists<Test> for MockContent {
  83. fn has_content(which: &ContentId<Test>) -> bool {
  84. *which == TEST_MOCK_EXISTING_CID
  85. }
  86. fn get_data_object(
  87. which: &ContentId<Test>,
  88. ) -> Result<data_directory::DataObject<Test>, data_directory::Error<Test>> {
  89. match *which {
  90. TEST_MOCK_EXISTING_CID => Ok(data_directory::DataObjectInternal {
  91. type_id: 1,
  92. size: 1234,
  93. added_at: data_directory::BlockAndTime {
  94. block: 10,
  95. time: 1024,
  96. },
  97. owner: StorageObjectOwner::Member(1),
  98. liaison: Some(TEST_MOCK_LIAISON_STORAGE_PROVIDER_ID),
  99. liaison_judgement: data_directory::LiaisonJudgement::Pending,
  100. ipfs_content_id: vec![],
  101. }),
  102. _ => Err(data_directory::Error::<Test>::CidNotFound),
  103. }
  104. }
  105. }
  106. // Workaround for https://github.com/rust-lang/rust/issues/26925 . Remove when sorted.
  107. #[derive(Clone, PartialEq, Eq, Debug)]
  108. pub struct Test;
  109. parameter_types! {
  110. pub const BlockHashCount: u64 = 250;
  111. pub const MaximumBlockWeight: u32 = 1024;
  112. pub const MaximumBlockLength: u32 = 2 * 1024;
  113. pub const AvailableBlockRatio: Perbill = Perbill::one();
  114. pub const MinimumPeriod: u64 = 5;
  115. }
  116. impl frame_system::Trait for Test {
  117. type BaseCallFilter = ();
  118. type Origin = Origin;
  119. type Call = ();
  120. type Index = u64;
  121. type BlockNumber = u64;
  122. type Hash = H256;
  123. type Hashing = BlakeTwo256;
  124. type AccountId = u64;
  125. type Lookup = IdentityLookup<Self::AccountId>;
  126. type Header = Header;
  127. type Event = MetaEvent;
  128. type BlockHashCount = BlockHashCount;
  129. type MaximumBlockWeight = MaximumBlockWeight;
  130. type DbWeight = ();
  131. type BlockExecutionWeight = ();
  132. type ExtrinsicBaseWeight = ();
  133. type MaximumExtrinsicWeight = ();
  134. type MaximumBlockLength = MaximumBlockLength;
  135. type AvailableBlockRatio = AvailableBlockRatio;
  136. type Version = ();
  137. type AccountData = balances::AccountData<u64>;
  138. type OnNewAccount = ();
  139. type OnKilledAccount = ();
  140. type SystemWeightInfo = ();
  141. type PalletInfo = ();
  142. }
  143. impl pallet_timestamp::Trait for Test {
  144. type Moment = u64;
  145. type OnTimestampSet = ();
  146. type MinimumPeriod = MinimumPeriod;
  147. type WeightInfo = ();
  148. }
  149. impl common::MembershipTypes for Test {
  150. type MemberId = u64;
  151. type ActorId = u64;
  152. }
  153. impl common::StorageOwnership for Test {
  154. type ChannelId = u64;
  155. type DAOId = u64;
  156. type ContentId = u64;
  157. type DataObjectTypeId = u64;
  158. }
  159. parameter_types! {
  160. pub const ExistentialDeposit: u32 = 0;
  161. pub const StakePoolId: [u8; 8] = *b"joystake";
  162. }
  163. impl balances::Trait for Test {
  164. type Balance = u64;
  165. type DustRemoval = ();
  166. type Event = MetaEvent;
  167. type ExistentialDeposit = ExistentialDeposit;
  168. type AccountStore = System;
  169. type WeightInfo = ();
  170. type MaxLocks = ();
  171. }
  172. impl GovernanceCurrency for Test {
  173. type Currency = balances::Module<Self>;
  174. }
  175. parameter_types! {
  176. pub const MaxWorkerNumberLimit: u32 = 3;
  177. }
  178. impl working_group::Trait<StorageWorkingGroupInstance> for Test {
  179. type Event = MetaEvent;
  180. type MaxWorkerNumberLimit = MaxWorkerNumberLimit;
  181. }
  182. impl data_object_type_registry::Trait for Test {
  183. type Event = MetaEvent;
  184. }
  185. impl data_directory::Trait for Test {
  186. type Event = MetaEvent;
  187. type IsActiveDataObjectType = AnyDataObjectTypeIsActive;
  188. type MemberOriginValidator = ();
  189. }
  190. impl common::origin::ActorOriginValidator<Origin, u64, u64> for () {
  191. fn ensure_actor_origin(origin: Origin, _account_id: u64) -> Result<u64, &'static str> {
  192. let signed_account_id = frame_system::ensure_signed(origin)?;
  193. Ok(signed_account_id)
  194. }
  195. }
  196. impl data_object_storage_registry::Trait for Test {
  197. type Event = MetaEvent;
  198. type DataObjectStorageRelationshipId = u64;
  199. type ContentIdExists = MockContent;
  200. }
  201. parameter_types! {
  202. pub const ScreenedMemberMaxInitialBalance: u64 = 500;
  203. }
  204. impl membership::Trait for Test {
  205. type Event = MetaEvent;
  206. type MemberId = u64;
  207. type SubscriptionId = u32;
  208. type PaidTermId = u32;
  209. type ActorId = u32;
  210. type ScreenedMemberMaxInitialBalance = ScreenedMemberMaxInitialBalance;
  211. }
  212. impl stake::Trait for Test {
  213. type Currency = Balances;
  214. type StakePoolId = StakePoolId;
  215. type StakingEventsHandler = ();
  216. type StakeId = u64;
  217. type SlashId = u64;
  218. }
  219. impl minting::Trait for Test {
  220. type Currency = Balances;
  221. type MintId = u64;
  222. }
  223. impl recurringrewards::Trait for Test {
  224. type PayoutStatusHandler = ();
  225. type RecipientId = u64;
  226. type RewardRelationshipId = u64;
  227. }
  228. impl hiring::Trait for Test {
  229. type OpeningId = u64;
  230. type ApplicationId = u64;
  231. type ApplicationDeactivatedHandler = ();
  232. type StakeHandlerProvider = hiring::Module<Self>;
  233. }
  234. pub struct ExtBuilder {
  235. voucher_objects_limit_upper_bound: u64,
  236. voucher_size_limit_upper_bound: u64,
  237. global_voucher: Voucher,
  238. default_voucher: Voucher,
  239. first_data_object_type_id: u64,
  240. first_content_id: u64,
  241. first_relationship_id: u64,
  242. first_metadata_id: u64,
  243. uploading_blocked: bool,
  244. }
  245. impl Default for ExtBuilder {
  246. fn default() -> Self {
  247. Self {
  248. voucher_objects_limit_upper_bound: DEFAULT_VOUCHER_OBJECTS_LIMIT_UPPER_BOUND,
  249. voucher_size_limit_upper_bound: DEFAULT_VOUCHER_SIZE_LIMIT_UPPER_BOUND,
  250. global_voucher: DEFAULT_GLOBAL_VOUCHER,
  251. default_voucher: DEFAULT_VOUCHER,
  252. first_data_object_type_id: 1,
  253. first_content_id: 2,
  254. first_relationship_id: 3,
  255. first_metadata_id: 4,
  256. uploading_blocked: DEFAULT_UPLOADING_BLOCKED_STATUS,
  257. }
  258. }
  259. }
  260. impl ExtBuilder {
  261. pub fn first_data_object_type_id(mut self, first_data_object_type_id: u64) -> Self {
  262. self.first_data_object_type_id = first_data_object_type_id;
  263. self
  264. }
  265. pub fn first_content_id(mut self, first_content_id: u64) -> Self {
  266. self.first_content_id = first_content_id;
  267. self
  268. }
  269. pub fn first_relationship_id(mut self, first_relationship_id: u64) -> Self {
  270. self.first_relationship_id = first_relationship_id;
  271. self
  272. }
  273. pub fn first_metadata_id(mut self, first_metadata_id: u64) -> Self {
  274. self.first_metadata_id = first_metadata_id;
  275. self
  276. }
  277. pub fn uploading_blocked_status(mut self, uploading_blocked: bool) -> Self {
  278. self.uploading_blocked = uploading_blocked;
  279. self
  280. }
  281. pub fn global_voucher(mut self, global_voucher: Voucher) -> Self {
  282. self.global_voucher = global_voucher;
  283. self
  284. }
  285. pub fn build(self) -> sp_io::TestExternalities {
  286. let mut t = frame_system::GenesisConfig::default()
  287. .build_storage::<Test>()
  288. .unwrap();
  289. data_directory::GenesisConfig::<Test> {
  290. voucher_size_limit_upper_bound: self.voucher_size_limit_upper_bound,
  291. voucher_objects_limit_upper_bound: self.voucher_objects_limit_upper_bound,
  292. global_voucher: self.global_voucher,
  293. default_voucher: self.default_voucher,
  294. data_object_by_content_id: vec![],
  295. vouchers: vec![],
  296. uploading_blocked: self.uploading_blocked,
  297. }
  298. .assimilate_storage(&mut t)
  299. .unwrap();
  300. data_object_type_registry::GenesisConfig::<Test> {
  301. first_data_object_type_id: self.first_data_object_type_id,
  302. }
  303. .assimilate_storage(&mut t)
  304. .unwrap();
  305. data_object_storage_registry::GenesisConfig::<Test> {
  306. first_relationship_id: self.first_relationship_id,
  307. }
  308. .assimilate_storage(&mut t)
  309. .unwrap();
  310. membership::GenesisConfig::<Test> {
  311. default_paid_membership_fee: 0,
  312. members: vec![membership::genesis::Member {
  313. member_id: 0,
  314. root_account: 1,
  315. controller_account: 1,
  316. handle: "alice".into(),
  317. avatar_uri: "".into(),
  318. about: "".into(),
  319. registered_at_time: 0,
  320. }],
  321. }
  322. .assimilate_storage(&mut t)
  323. .unwrap();
  324. t.into()
  325. }
  326. }
  327. pub type TestDataObjectType = data_object_type_registry::DataObjectType;
  328. pub type Balances = balances::Module<Test>;
  329. pub type System = frame_system::Module<Test>;
  330. pub type TestDataObjectTypeRegistry = data_object_type_registry::Module<Test>;
  331. pub type TestDataDirectory = data_directory::Module<Test>;
  332. pub type TestDataObjectStorageRegistry = data_object_storage_registry::Module<Test>;
  333. pub fn with_default_mock_builder<R, F: FnOnce() -> R>(f: F) -> R {
  334. ExtBuilder::default()
  335. .first_data_object_type_id(TEST_FIRST_DATA_OBJECT_TYPE_ID)
  336. .first_content_id(TEST_FIRST_CONTENT_ID)
  337. .first_relationship_id(TEST_FIRST_RELATIONSHIP_ID)
  338. .first_metadata_id(TEST_FIRST_METADATA_ID)
  339. .build()
  340. .execute_with(|| f())
  341. }
  342. pub(crate) fn hire_storage_provider() -> (u64, u32) {
  343. let storage_provider_id = 1;
  344. let role_account_id = 1;
  345. let storage_provider = working_group::Worker {
  346. member_id: 1,
  347. role_account_id,
  348. reward_relationship: None,
  349. role_stake_profile: None,
  350. };
  351. <working_group::WorkerById<Test, StorageWorkingGroupInstance>>::insert(
  352. storage_provider_id,
  353. storage_provider,
  354. );
  355. (role_account_id, storage_provider_id)
  356. }
  357. // Recommendation from Parity on testing on_finalize
  358. // https://substrate.dev/docs/en/next/development/module/tests
  359. pub fn run_to_block(n: u64) {
  360. while System::block_number() < n {
  361. <System as OnFinalize<u64>>::on_finalize(System::block_number());
  362. <TestDataObjectTypeRegistry as OnFinalize<u64>>::on_finalize(System::block_number());
  363. <TestDataDirectory as OnFinalize<u64>>::on_finalize(System::block_number());
  364. <TestDataObjectStorageRegistry as OnFinalize<u64>>::on_finalize(System::block_number());
  365. System::set_block_number(System::block_number() + 1);
  366. <System as OnInitialize<u64>>::on_initialize(System::block_number());
  367. <TestDataObjectTypeRegistry as OnInitialize<u64>>::on_initialize(System::block_number());
  368. <TestDataDirectory as OnInitialize<u64>>::on_initialize(System::block_number());
  369. <TestDataObjectStorageRegistry as OnInitialize<u64>>::on_initialize(System::block_number());
  370. }
  371. }