tests.rs 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285
  1. #![cfg(test)]
  2. use super::genesis;
  3. use super::mock::*;
  4. use frame_support::{assert_err, assert_ok, traits::Currency, StorageValue};
  5. use sp_arithmetic::traits::One;
  6. use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
  7. use system::RawOrigin;
  8. use common::constraints::InputValidationLengthConstraint;
  9. use hiring;
  10. #[test]
  11. fn create_channel_success() {
  12. TestExternalitiesBuilder::<Test>::default()
  13. .build()
  14. .execute_with(|| {
  15. /*
  16. Events are not emitted on block 0.
  17. So any dispatchable calls made during genesis block formation will have no events emitted.
  18. https://substrate.dev/recipes/2-appetizers/4-events.html
  19. */
  20. run_to_block(1);
  21. // Add channel creator as member
  22. let channel_creator_member_root_and_controller_account = 12312;
  23. let channel_creator_member_id = add_member(
  24. channel_creator_member_root_and_controller_account,
  25. to_vec(CHANNEL_CREATOR_HANDLE),
  26. );
  27. let fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  28. channel_creator_member_id,
  29. None,
  30. );
  31. fixture.call_and_assert_success();
  32. });
  33. }
  34. #[test]
  35. fn create_channel_is_not_a_member() {
  36. TestExternalitiesBuilder::<Test>::default()
  37. .build()
  38. .execute_with(|| {
  39. let channel_creator_member_id = add_channel_creator_member();
  40. let mut fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  41. channel_creator_member_id,
  42. None,
  43. );
  44. // Change to invalid member id, i.e. != channel_creator_member_id
  45. fixture.channel_creator_member_id = fixture.channel_creator_member_id
  46. + <<Test as membership::Trait>::MemberId as One>::one();
  47. fixture.call_and_assert_error(MSG_MEMBER_ID_INVALID);
  48. });
  49. }
  50. #[test]
  51. fn create_channel_not_enabled() {
  52. TestExternalitiesBuilder::<Test>::default()
  53. .build()
  54. .execute_with(|| {
  55. add_member_and_set_as_lead();
  56. set_channel_creation_enabled(false);
  57. let channel_creator_member_id = add_channel_creator_member();
  58. let fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  59. channel_creator_member_id,
  60. None,
  61. );
  62. fixture.call_and_assert_error(MSG_CHANNEL_CREATION_DISABLED);
  63. });
  64. }
  65. #[test]
  66. fn create_channel_with_bad_member_role_account() {
  67. TestExternalitiesBuilder::<Test>::default()
  68. .build()
  69. .execute_with(|| {
  70. let channel_creator_member_id = add_channel_creator_member();
  71. let fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  72. channel_creator_member_id,
  73. Some(0),
  74. );
  75. fixture.call_and_assert_error(MSG_SIGNER_NOT_CONTROLLER_ACCOUNT);
  76. });
  77. }
  78. #[test]
  79. fn create_channel_handle_too_long() {
  80. TestExternalitiesBuilder::<Test>::default()
  81. .build()
  82. .execute_with(|| {
  83. let channel_creator_member_id = add_channel_creator_member();
  84. let mut fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  85. channel_creator_member_id,
  86. None,
  87. );
  88. fixture.channel_handle =
  89. generate_too_long_length_buffer(&ChannelHandleConstraint::get());
  90. fixture.call_and_assert_error(MSG_CHANNEL_HANDLE_TOO_LONG);
  91. });
  92. }
  93. #[test]
  94. fn create_channel_handle_too_short() {
  95. TestExternalitiesBuilder::<Test>::default()
  96. .build()
  97. .execute_with(|| {
  98. let channel_creator_member_id = add_channel_creator_member();
  99. let mut fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  100. channel_creator_member_id,
  101. None,
  102. );
  103. fixture.channel_handle =
  104. generate_too_short_length_buffer(&ChannelHandleConstraint::get());
  105. fixture.call_and_assert_error(MSG_CHANNEL_HANDLE_TOO_SHORT);
  106. });
  107. }
  108. #[test]
  109. fn create_channel_description_too_long() {
  110. TestExternalitiesBuilder::<Test>::default()
  111. .build()
  112. .execute_with(|| {
  113. let channel_creator_member_id = add_channel_creator_member();
  114. let mut fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  115. channel_creator_member_id,
  116. None,
  117. );
  118. fixture.description = Some(generate_too_long_length_buffer(
  119. &ChannelDescriptionConstraint::get(),
  120. ));
  121. fixture.call_and_assert_error(MSG_CHANNEL_DESCRIPTION_TOO_LONG);
  122. });
  123. }
  124. #[test]
  125. fn create_channel_description_too_short() {
  126. TestExternalitiesBuilder::<Test>::default()
  127. .build()
  128. .execute_with(|| {
  129. let channel_creator_member_id = add_channel_creator_member();
  130. let mut fixture = CreateChannelFixture::make_valid_unpulished_video_channel_for(
  131. channel_creator_member_id,
  132. None,
  133. );
  134. fixture.description = Some(generate_too_short_length_buffer(
  135. &ChannelDescriptionConstraint::get(),
  136. ));
  137. fixture.call_and_assert_error(MSG_CHANNEL_DESCRIPTION_TOO_SHORT);
  138. });
  139. }
  140. #[test]
  141. fn transfer_channel_ownership_success() {
  142. TestExternalitiesBuilder::<Test>::default()
  143. .build()
  144. .execute_with(|| {
  145. /*
  146. Events are not emitted on block 0.
  147. So any dispatchable calls made during genesis block formation will have no events emitted.
  148. https://substrate.dev/recipes/2-appetizers/4-events.html
  149. */
  150. run_to_block(1);
  151. // Add channel creator as member
  152. let channel_creator_member_root_and_controller_account_1 = 1111;
  153. let channel_creator_member_root_and_controller_account_2 = 2222;
  154. let channel_creator_member_id_1 = add_member(
  155. channel_creator_member_root_and_controller_account_1,
  156. to_vec(CHANNEL_CREATOR_HANDLE),
  157. );
  158. let channel_creator_member_id_2 = add_member(
  159. channel_creator_member_root_and_controller_account_2,
  160. to_vec(CHANNEL_CREATOR_HANDLE2),
  161. );
  162. let create_channel_fixture =
  163. CreateChannelFixture::make_valid_unpulished_video_channel_for(
  164. channel_creator_member_id_1,
  165. None,
  166. );
  167. let channel_id = create_channel_fixture.call_and_assert_success();
  168. let original_channel = ChannelById::<Test>::get(channel_id);
  169. let new_role_account = 3333;
  170. let transfer_result = ContentWorkingGroup::transfer_channel_ownership(
  171. Origin::signed(create_channel_fixture.channel_creator_role_account),
  172. channel_id,
  173. channel_creator_member_id_2,
  174. new_role_account,
  175. );
  176. assert_ok!(transfer_result);
  177. let updated_channel = ChannelById::<Test>::get(channel_id);
  178. assert_eq!(
  179. updated_channel,
  180. Channel {
  181. owner: channel_creator_member_id_2,
  182. role_account: new_role_account,
  183. ..original_channel
  184. }
  185. );
  186. });
  187. }
  188. #[test]
  189. fn update_channel_as_owner_success() {}
  190. struct UpdateChannelAsCurationActorFixture {
  191. pub origin: Origin,
  192. pub curation_actor: CurationActor<CuratorId<Test>>,
  193. pub new_verified: Option<bool>,
  194. pub new_description: Option<OptionalText>,
  195. pub new_curation_status: Option<ChannelCurationStatus>,
  196. }
  197. impl UpdateChannelAsCurationActorFixture {
  198. fn update_channel_as_curation_actor(
  199. &self,
  200. channel_id: ChannelId<Test>,
  201. ) -> Result<(), &'static str> {
  202. ContentWorkingGroup::update_channel_as_curation_actor(
  203. self.origin.clone(),
  204. self.curation_actor.clone(),
  205. channel_id,
  206. self.new_verified,
  207. self.new_curation_status,
  208. )
  209. .map_err(<&str>::from)
  210. }
  211. pub fn call_and_assert_success(&self, channel_id: ChannelId<Test>) {
  212. let old_channel = ChannelById::<Test>::get(channel_id);
  213. let upd_verified = self.new_verified.unwrap_or(old_channel.verified);
  214. let upd_description = self
  215. .new_description
  216. .clone()
  217. .unwrap_or(old_channel.description);
  218. let upd_curation_status = self
  219. .new_curation_status
  220. .unwrap_or(old_channel.curation_status);
  221. let expected_updated_channel = Channel {
  222. verified: upd_verified,
  223. handle: old_channel.handle,
  224. title: old_channel.title,
  225. description: upd_description,
  226. avatar: old_channel.avatar,
  227. banner: old_channel.banner,
  228. content: old_channel.content,
  229. owner: old_channel.owner,
  230. role_account: old_channel.role_account,
  231. publication_status: old_channel.publication_status,
  232. curation_status: upd_curation_status,
  233. created: old_channel.created,
  234. principal_id: old_channel.principal_id,
  235. };
  236. // Call and check result
  237. let call_result = self.update_channel_as_curation_actor(channel_id);
  238. assert_eq!(call_result, Ok(()));
  239. // Event triggered
  240. let event_channel_id = Self::get_event_deposited();
  241. assert_eq!(event_channel_id, channel_id);
  242. // Channel has been updated correctly
  243. assert!(ChannelById::<Test>::contains_key(channel_id));
  244. let updated_channel = ChannelById::<Test>::get(channel_id);
  245. assert_eq!(updated_channel, expected_updated_channel);
  246. }
  247. fn get_event_deposited() -> crate::ChannelId<Test> {
  248. if let mock::TestEvent::lib(ref x) = System::events().last().unwrap().event {
  249. if let crate::RawEvent::ChannelUpdatedByCurationActor(ref channel_id) = x {
  250. return channel_id.clone();
  251. } else {
  252. panic!("Event was not ChannelUpdatedByCurationActor.")
  253. }
  254. } else {
  255. panic!("No event deposited.")
  256. }
  257. }
  258. }
  259. #[test]
  260. fn update_channel_as_curation_actor_success() {
  261. TestExternalitiesBuilder::<Test>::default()
  262. .build()
  263. .execute_with(|| {
  264. // Add lead and hire curator
  265. let curator_params = AddMemberAndApplyOnOpeningParams::new(
  266. 2222,
  267. to_vec("yoyoyo0"), // generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  268. 2222 * 2,
  269. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  270. );
  271. // Hire curator
  272. let setup_and_fill_opening_result =
  273. setup_and_fill_opening(&vec![FillOpeningApplicantParams::new(
  274. curator_params.clone(),
  275. true,
  276. )]);
  277. let curator_id = match setup_and_fill_opening_result.application_outomes[0] {
  278. FillOpeningApplicantOutcome::Hired { curator_id } => curator_id,
  279. _ => panic!(),
  280. };
  281. // Make channel
  282. let channel_creator_member_id = add_channel_creator_member();
  283. let channel_id = channel_creator_member_id;
  284. CreateChannelFixture::make_valid_unpulished_video_channel_for(
  285. channel_creator_member_id,
  286. None,
  287. )
  288. .call_and_assert_success();
  289. // Update channel as curator
  290. UpdateChannelAsCurationActorFixture {
  291. origin: Origin::signed(curator_params.curator_applicant_role_account),
  292. curation_actor: CurationActor::Curator(curator_id),
  293. new_verified: Some(true),
  294. new_description: None, // don't touch!
  295. new_curation_status: Some(ChannelCurationStatus::Censored),
  296. }
  297. .call_and_assert_success(channel_id);
  298. });
  299. }
  300. #[test]
  301. fn add_curator_opening_success() {
  302. TestExternalitiesBuilder::<Test>::default()
  303. .build()
  304. .execute_with(|| {
  305. /*
  306. * Setup
  307. */
  308. add_member_and_set_as_lead();
  309. let expected_opening_id = hiring::NextOpeningId::<Test>::get();
  310. let expected_curator_opening_id = NextCuratorOpeningId::<Test>::get();
  311. /*
  312. * Test
  313. */
  314. // Add opening
  315. let activate_at = hiring::ActivateOpeningAt::ExactBlock(34);
  316. let human_readable_text =
  317. generate_valid_length_buffer(&OpeningHumanReadableText::get());
  318. assert_eq!(
  319. ContentWorkingGroup::add_curator_opening(
  320. Origin::signed(LEAD_ROLE_ACCOUNT),
  321. activate_at.clone(),
  322. get_baseline_opening_policy(),
  323. human_readable_text.clone()
  324. )
  325. .unwrap(),
  326. ()
  327. );
  328. assert_eq!(
  329. get_last_event_or_panic(),
  330. crate::RawEvent::CuratorOpeningAdded(expected_curator_opening_id)
  331. );
  332. // Assert that given opening id has been added,
  333. // and has the right properties.
  334. assert!(crate::CuratorOpeningById::<Test>::contains_key(
  335. expected_curator_opening_id
  336. ));
  337. let created_curator_opening =
  338. crate::CuratorOpeningById::<Test>::get(expected_curator_opening_id);
  339. let expected_curator_opening = CuratorOpening {
  340. opening_id: expected_opening_id,
  341. curator_applications: BTreeSet::new(),
  342. policy_commitment: get_baseline_opening_policy(),
  343. };
  344. assert_eq!(created_curator_opening, expected_curator_opening);
  345. // Assert that next id incremented.
  346. assert_eq!(
  347. crate::NextCuratorOpeningId::<Test>::get(),
  348. expected_opening_id + 1
  349. );
  350. /*
  351. * TODO: add assertion abouot side-effect in hiring module,
  352. * this is where state of application has fundamentally changed.
  353. */
  354. });
  355. }
  356. #[test]
  357. fn accept_curator_applications_success() {
  358. TestExternalitiesBuilder::<Test>::default()
  359. .build()
  360. .execute_with(|| {
  361. /*
  362. * Setup
  363. */
  364. add_member_and_set_as_lead();
  365. let curator_opening_id = add_curator_opening();
  366. /*
  367. * Test
  368. */
  369. assert_eq!(
  370. ContentWorkingGroup::accept_curator_applications(
  371. Origin::signed(LEAD_ROLE_ACCOUNT),
  372. curator_opening_id
  373. )
  374. .unwrap(),
  375. ()
  376. );
  377. assert_eq!(
  378. get_last_event_or_panic(),
  379. crate::RawEvent::AcceptedCuratorApplications(curator_opening_id)
  380. )
  381. /*
  382. * TODO: add assertion abouot side-effect in hiring module,
  383. * this is where state of application has fundamentally changed.
  384. */
  385. });
  386. }
  387. #[test]
  388. fn begin_curator_applicant_review_success() {
  389. TestExternalitiesBuilder::<Test>::default()
  390. .build()
  391. .execute_with(|| {
  392. /*
  393. * Setup
  394. */
  395. let normal_opening_constructed = setup_normal_accepting_opening();
  396. let _ = add_member_and_apply_on_opening(
  397. normal_opening_constructed.curator_opening_id,
  398. 333,
  399. to_vec("CuratorWannabe"),
  400. 11111,
  401. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  402. );
  403. /*
  404. * Test
  405. */
  406. assert_eq!(
  407. ContentWorkingGroup::begin_curator_applicant_review(
  408. Origin::signed(LEAD_ROLE_ACCOUNT),
  409. normal_opening_constructed.curator_opening_id
  410. )
  411. .unwrap(),
  412. ()
  413. );
  414. assert_eq!(
  415. get_last_event_or_panic(),
  416. crate::RawEvent::BeganCuratorApplicationReview(
  417. normal_opening_constructed.curator_opening_id
  418. )
  419. );
  420. /*
  421. * TODO: add assertion abouot side-effect in hiring module,
  422. * this is where state of application has fundamentally changed.
  423. */
  424. // Assert opening is in opening stage... hiring::ActiveOpeningStage::ReviewPeriod
  425. let opening =
  426. <hiring::OpeningById<Test>>::get(&normal_opening_constructed.curator_opening_id);
  427. match opening.stage {
  428. hiring::OpeningStage::Active { stage, .. } => {
  429. match stage {
  430. hiring::ActiveOpeningStage::ReviewPeriod {
  431. started_review_period_at_block,
  432. ..
  433. } => {
  434. /* OK */
  435. // assert_eq!(started_accepting_applicants_at_block, 0);
  436. assert_eq!(started_review_period_at_block, System::block_number());
  437. }
  438. _ => panic!("ActiveOpeningStage must be in ReviewPeriod"),
  439. }
  440. }
  441. _ => panic!("OpeningStage must be Active"),
  442. };
  443. });
  444. }
  445. #[test]
  446. fn fill_curator_opening_success() {
  447. TestExternalitiesBuilder::<Test>::default()
  448. .build()
  449. .execute_with(|| {
  450. /*
  451. * Setup
  452. */
  453. let applicants = vec![
  454. FillOpeningApplicantParams::new(
  455. AddMemberAndApplyOnOpeningParams::new(
  456. 2222,
  457. to_vec("yoyoyo0"), // generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  458. 2222 * 2,
  459. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  460. ),
  461. true,
  462. ),
  463. FillOpeningApplicantParams::new(
  464. AddMemberAndApplyOnOpeningParams::new(
  465. 3333,
  466. to_vec("yoyoyo1"), // generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  467. 3333 * 2,
  468. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  469. ),
  470. true,
  471. ),
  472. FillOpeningApplicantParams::new(
  473. AddMemberAndApplyOnOpeningParams::new(
  474. 5555,
  475. to_vec("yoyoyo2"), // generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  476. 5555 * 2,
  477. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  478. ),
  479. false,
  480. ),
  481. FillOpeningApplicantParams::new(
  482. AddMemberAndApplyOnOpeningParams::new(
  483. 6666,
  484. to_vec("yoyoyo3"), // generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  485. 6666 * 2,
  486. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  487. ),
  488. true,
  489. ),
  490. ];
  491. /*
  492. * Exercise and assert
  493. */
  494. setup_and_fill_opening(&applicants);
  495. });
  496. }
  497. #[test]
  498. fn withdraw_curator_application_success() {
  499. TestExternalitiesBuilder::<Test>::default()
  500. .build()
  501. .execute_with(|| {
  502. /*
  503. * Setup
  504. */
  505. let normal_opening_constructed = setup_normal_accepting_opening();
  506. let curator_applicant_root_and_controller_account = 333;
  507. let curator_applicant_role_account = 11111;
  508. let human_readable_text =
  509. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get());
  510. let result = add_member_and_apply_on_opening(
  511. normal_opening_constructed.curator_opening_id,
  512. curator_applicant_root_and_controller_account,
  513. to_vec("CuratorWannabe"),
  514. curator_applicant_role_account,
  515. human_readable_text,
  516. );
  517. /*
  518. * Test
  519. */
  520. assert_eq!(
  521. ContentWorkingGroup::withdraw_curator_application(
  522. Origin::signed(curator_applicant_role_account),
  523. result.curator_application_id
  524. )
  525. .unwrap(),
  526. ()
  527. );
  528. // Event was triggered
  529. assert_eq!(
  530. get_last_event_or_panic(),
  531. crate::RawEvent::CuratorApplicationWithdrawn(result.curator_application_id)
  532. );
  533. /*
  534. * TODO: add assertion abouot side-effect in hiring module,
  535. * this is where state of application has fundamentally changed.
  536. */
  537. });
  538. }
  539. #[test]
  540. fn terminate_curator_application_success() {
  541. TestExternalitiesBuilder::<Test>::default()
  542. .build()
  543. .execute_with(|| {
  544. /*
  545. * Setup
  546. */
  547. let normal_opening_constructed = setup_normal_accepting_opening();
  548. let result = add_member_and_apply_on_opening(
  549. normal_opening_constructed.curator_opening_id,
  550. 333,
  551. to_vec("CuratorWannabe"),
  552. 11111,
  553. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  554. );
  555. /*
  556. * Test
  557. */
  558. assert_eq!(
  559. ContentWorkingGroup::terminate_curator_application(
  560. Origin::signed(LEAD_ROLE_ACCOUNT),
  561. normal_opening_constructed.curator_opening_id
  562. )
  563. .unwrap(),
  564. ()
  565. );
  566. assert_eq!(
  567. get_last_event_or_panic(),
  568. crate::RawEvent::CuratorApplicationTerminated(result.curator_application_id)
  569. );
  570. /*
  571. * TODO: add assertion abouot side-effect in hiring module,
  572. * this is where state of application has fundamentally changed.
  573. */
  574. });
  575. }
  576. #[test]
  577. fn apply_on_curator_opening_success() {
  578. TestExternalitiesBuilder::<Test>::default()
  579. .build()
  580. .execute_with(|| {
  581. /*
  582. * Setup
  583. */
  584. let normal_opening_constructed = setup_normal_accepting_opening();
  585. // Add curator membership
  586. let curator_applicant_root_and_controller_account = 72618;
  587. let curator_applicant_member_id = add_member(
  588. curator_applicant_root_and_controller_account,
  589. to_vec("IwillTrytoapplyhere"),
  590. );
  591. let curator_applicant_role_account = 8881111;
  592. let role_stake_balance = get_baseline_opening_policy()
  593. .role_staking_policy
  594. .unwrap()
  595. .amount;
  596. let application_stake_balance = get_baseline_opening_policy()
  597. .application_staking_policy
  598. .unwrap()
  599. .amount;
  600. let total_balance = role_stake_balance + application_stake_balance;
  601. let source_account = curator_applicant_root_and_controller_account;
  602. // Credit staking source account
  603. let _ = balances::Module::<Test>::deposit_creating(&source_account, total_balance);
  604. let human_readable_text = generate_valid_length_buffer(&ChannelHandleConstraint::get());
  605. let expected_curator_application_id = NextCuratorApplicationId::<Test>::get();
  606. let old_curator_opening =
  607. CuratorOpeningById::<Test>::get(normal_opening_constructed.curator_opening_id);
  608. let new_curator_application_id = NextCuratorApplicationId::<Test>::get();
  609. /*
  610. * Test
  611. */
  612. assert_eq!(
  613. ContentWorkingGroup::apply_on_curator_opening(
  614. Origin::signed(curator_applicant_root_and_controller_account),
  615. curator_applicant_member_id,
  616. normal_opening_constructed.curator_opening_id,
  617. curator_applicant_role_account,
  618. Some(role_stake_balance),
  619. Some(application_stake_balance),
  620. human_readable_text
  621. )
  622. .unwrap(),
  623. ()
  624. );
  625. assert_eq!(
  626. get_last_event_or_panic(),
  627. crate::RawEvent::AppliedOnCuratorOpening(
  628. normal_opening_constructed.curator_opening_id,
  629. new_curator_application_id
  630. )
  631. );
  632. assert!(CuratorApplicationById::<Test>::contains_key(
  633. new_curator_application_id
  634. ));
  635. // Assert that appropriate application has been added
  636. let new_curator_application =
  637. CuratorApplicationById::<Test>::get(new_curator_application_id);
  638. let expected_curator_application = CuratorApplication {
  639. role_account: curator_applicant_role_account,
  640. curator_opening_id: normal_opening_constructed.curator_opening_id,
  641. member_id: curator_applicant_member_id,
  642. application_id: expected_curator_application_id,
  643. };
  644. assert_eq!(expected_curator_application, new_curator_application);
  645. // Assert that the opening has had the application added to application list
  646. let mut singleton = BTreeSet::new(); // Unavoidable mutable, BTreeSet can only be populated this way.
  647. singleton.insert(new_curator_application_id);
  648. let new_curator_applications = old_curator_opening
  649. .curator_applications
  650. .union(&singleton)
  651. .cloned()
  652. .collect();
  653. let expected_curator_opening = CuratorOpening {
  654. curator_applications: new_curator_applications,
  655. ..old_curator_opening
  656. };
  657. let new_curator_opening =
  658. CuratorOpeningById::<Test>::get(normal_opening_constructed.curator_opening_id);
  659. assert_eq!(expected_curator_opening, new_curator_opening);
  660. });
  661. }
  662. #[test]
  663. fn multiple_applications_by_same_member_to_opening_fails() {
  664. TestExternalitiesBuilder::<Test>::default()
  665. .build()
  666. .execute_with(|| {
  667. /*
  668. * Setup
  669. */
  670. let normal_opening_constructed = setup_normal_accepting_opening();
  671. // Add curator membership
  672. let curator_applicant_root_and_controller_account = 72618;
  673. let curator_applicant_member_id = add_member(
  674. curator_applicant_root_and_controller_account,
  675. to_vec("IwillTrytoapplyhere"),
  676. );
  677. let curator_applicant_role_account = 8881111;
  678. let role_stake_balance = get_baseline_opening_policy()
  679. .role_staking_policy
  680. .unwrap()
  681. .amount;
  682. let application_stake_balance = get_baseline_opening_policy()
  683. .application_staking_policy
  684. .unwrap()
  685. .amount;
  686. let total_balance = role_stake_balance + application_stake_balance;
  687. let source_account = curator_applicant_root_and_controller_account;
  688. // Credit staking source account with enough funds for two applications,
  689. // because we don't want our second application to fail for lack of funds
  690. let _ = balances::Module::<Test>::deposit_creating(&source_account, total_balance * 2);
  691. let human_readable_text = generate_valid_length_buffer(&ChannelHandleConstraint::get());
  692. /*
  693. * Test
  694. */
  695. // First application should work
  696. assert_ok!(ContentWorkingGroup::apply_on_curator_opening(
  697. Origin::signed(curator_applicant_root_and_controller_account),
  698. curator_applicant_member_id,
  699. normal_opening_constructed.curator_opening_id,
  700. curator_applicant_role_account,
  701. Some(role_stake_balance),
  702. Some(application_stake_balance),
  703. human_readable_text.clone()
  704. ));
  705. // Second application should fail since
  706. // first application is still active
  707. assert_err!(
  708. ContentWorkingGroup::apply_on_curator_opening(
  709. Origin::signed(curator_applicant_root_and_controller_account),
  710. curator_applicant_member_id,
  711. normal_opening_constructed.curator_opening_id,
  712. curator_applicant_role_account,
  713. Some(role_stake_balance),
  714. Some(application_stake_balance),
  715. human_readable_text
  716. ),
  717. MSG_MEMBER_HAS_ACTIVE_APPLICATION_ON_OPENING
  718. );
  719. });
  720. }
  721. struct UpdateCuratorRoleAccountFixture {
  722. pub origin: Origin,
  723. pub member_id: <Test as membership::Trait>::MemberId,
  724. pub curator_id: CuratorId<Test>,
  725. pub new_role_account: <Test as system::Trait>::AccountId,
  726. }
  727. impl UpdateCuratorRoleAccountFixture {
  728. fn call(&self) -> Result<(), &'static str> {
  729. ContentWorkingGroup::update_curator_role_account(
  730. self.origin.clone(),
  731. self.member_id,
  732. self.curator_id,
  733. self.new_role_account,
  734. )
  735. .map_err(<&str>::from)
  736. }
  737. pub fn call_and_assert_success(&self) {
  738. let original_curator = CuratorById::<Test>::get(self.curator_id);
  739. let call_result = self.call();
  740. assert_eq!(call_result, Ok(()));
  741. let updated_curator = CuratorById::<Test>::get(self.curator_id);
  742. assert_eq!(
  743. crate::Curator {
  744. role_account: self.new_role_account,
  745. ..original_curator
  746. },
  747. updated_curator
  748. );
  749. let (event_curator_id, event_new_role_account) =
  750. if let mock::TestEvent::lib(ref x) = System::events().last().unwrap().event {
  751. if let crate::RawEvent::CuratorRoleAccountUpdated(
  752. ref curator_id,
  753. ref new_role_account,
  754. ) = x
  755. {
  756. (curator_id.clone(), new_role_account.clone())
  757. } else {
  758. panic!("Event was not CuratorRoleAccountUpdated.")
  759. }
  760. } else {
  761. panic!("No event deposited.")
  762. };
  763. assert_eq!(self.curator_id, event_curator_id);
  764. assert_eq!(self.new_role_account, event_new_role_account);
  765. }
  766. }
  767. #[test]
  768. fn update_curator_role_account_success() {
  769. TestExternalitiesBuilder::<Test>::default()
  770. .build()
  771. .execute_with(|| {
  772. let result = setup_lead_and_hire_curator();
  773. let fixture = UpdateCuratorRoleAccountFixture {
  774. origin: Origin::signed(
  775. result
  776. .curator_params()
  777. .curator_applicant_root_and_controller_account,
  778. ),
  779. member_id: result.curator_member_id(),
  780. curator_id: result.curator_id(),
  781. new_role_account: 777777,
  782. };
  783. fixture.call_and_assert_success();
  784. });
  785. }
  786. struct UpdateCuratorRewardAccountFixture {
  787. pub origin: Origin,
  788. pub curator_id: CuratorId<Test>,
  789. pub new_reward_account: <Test as system::Trait>::AccountId,
  790. }
  791. impl UpdateCuratorRewardAccountFixture {
  792. #[allow(dead_code)] // delete if the method is unnecessary
  793. fn call(&self) -> Result<(), &'static str> {
  794. ContentWorkingGroup::update_curator_reward_account(
  795. self.origin.clone(),
  796. self.curator_id,
  797. self.new_reward_account,
  798. )
  799. .map_err(<&str>::from)
  800. }
  801. #[allow(dead_code)] // delete if the method is unnecessary
  802. pub fn call_and_assert_success(&self) {
  803. let _original_curator = CuratorById::<Test>::get(self.curator_id);
  804. let call_result = self.call();
  805. assert_eq!(call_result, Ok(()));
  806. /*
  807. Actually checking new reward account requires checking call to token mint module, but we cannot do that properly yet.
  808. */
  809. let (event_curator_id, event_reward_account) =
  810. if let mock::TestEvent::lib(ref x) = System::events().last().unwrap().event {
  811. if let crate::RawEvent::CuratorRewardAccountUpdated(
  812. ref curator_id,
  813. ref reward_account,
  814. ) = x
  815. {
  816. (curator_id.clone(), reward_account.clone())
  817. } else {
  818. panic!("Event was not CuratorRewardAccountUpdated.")
  819. }
  820. } else {
  821. panic!("No event deposited.")
  822. };
  823. assert_eq!(self.curator_id, event_curator_id);
  824. assert_eq!(self.new_reward_account, event_reward_account);
  825. }
  826. }
  827. #[test]
  828. fn update_curator_reward_account_success() {
  829. TestExternalitiesBuilder::<Test>::default()
  830. .build()
  831. .execute_with(|| {
  832. let result = setup_lead_and_hire_curator();
  833. let _fixture = UpdateCuratorRewardAccountFixture {
  834. origin: Origin::signed(result.curator_params().curator_applicant_role_account),
  835. curator_id: result.curator_id(),
  836. new_reward_account: 123321,
  837. };
  838. // TEMPORARILY DISABLED
  839. //fixture.call_and_assert_success();
  840. });
  841. }
  842. struct LeaveCuratorRoleFixture {
  843. pub origin: Origin,
  844. pub curator_id: CuratorId<Test>,
  845. pub rationale_text: Vec<u8>,
  846. }
  847. impl LeaveCuratorRoleFixture {
  848. fn call(&self) -> Result<(), &'static str> {
  849. ContentWorkingGroup::leave_curator_role(
  850. self.origin.clone(),
  851. self.curator_id,
  852. self.rationale_text.clone(),
  853. )
  854. .map_err(<&str>::from)
  855. }
  856. pub fn call_and_assert_success(&self) {
  857. let original_curator = CuratorById::<Test>::get(self.curator_id);
  858. let call_result = self.call();
  859. assert_eq!(call_result, Ok(()));
  860. let expected_curator = Curator {
  861. stage: CuratorRoleStage::Unstaking(CuratorExitSummary::new(
  862. &CuratorExitInitiationOrigin::Curator,
  863. &1,
  864. &self.rationale_text,
  865. )),
  866. ..(original_curator.clone())
  867. };
  868. let updated_curator = CuratorById::<Test>::get(self.curator_id);
  869. assert_eq!(updated_curator, expected_curator);
  870. assert_eq!(
  871. get_last_event_or_panic(),
  872. crate::RawEvent::CuratorUnstaking(self.curator_id)
  873. );
  874. // Tracking unstaking
  875. let curator_role_stake_id = original_curator.role_stake_profile.unwrap().stake_id;
  876. assert!(UnstakerByStakeId::<Test>::contains_key(
  877. curator_role_stake_id
  878. ));
  879. let unstaker = UnstakerByStakeId::<Test>::get(curator_role_stake_id);
  880. assert_eq!(unstaker, WorkingGroupUnstaker::Curator(self.curator_id));
  881. /*
  882. * TODO: Missing checks to calls to
  883. * recurringrewards, stake
  884. */
  885. }
  886. }
  887. #[test]
  888. fn leave_curator_role_success() {
  889. TestExternalitiesBuilder::<Test>::default()
  890. .build()
  891. .execute_with(|| {
  892. let result = setup_lead_and_hire_curator();
  893. let fixture = LeaveCuratorRoleFixture {
  894. origin: Origin::signed(result.curator_params().curator_applicant_role_account),
  895. curator_id: result.curator_id(),
  896. rationale_text: "I am sick of this horrible thing".as_bytes().to_vec(),
  897. };
  898. fixture.call_and_assert_success();
  899. });
  900. }
  901. struct TerminateCuratorRoleFixture {
  902. pub origin: Origin,
  903. pub curator_id: CuratorId<Test>,
  904. pub rationale_text: Vec<u8>,
  905. }
  906. impl TerminateCuratorRoleFixture {
  907. fn call(&self) -> Result<(), &'static str> {
  908. ContentWorkingGroup::terminate_curator_role(
  909. self.origin.clone(),
  910. self.curator_id,
  911. self.rationale_text.clone(),
  912. )
  913. .map_err(<&str>::from)
  914. }
  915. pub fn call_and_assert_success(&self) {
  916. let original_curator = CuratorById::<Test>::get(self.curator_id);
  917. let call_result = self.call();
  918. assert_eq!(call_result, Ok(()));
  919. let expected_curator = Curator {
  920. stage: CuratorRoleStage::Unstaking(CuratorExitSummary::new(
  921. &CuratorExitInitiationOrigin::Lead,
  922. &1,
  923. &self.rationale_text,
  924. )),
  925. ..(original_curator.clone())
  926. };
  927. let updated_curator = CuratorById::<Test>::get(self.curator_id);
  928. assert_eq!(updated_curator, expected_curator);
  929. assert_eq!(
  930. get_last_event_or_panic(),
  931. crate::RawEvent::CuratorUnstaking(self.curator_id)
  932. );
  933. // Tracking unstaking
  934. let curator_role_stake_id = original_curator.role_stake_profile.unwrap().stake_id;
  935. assert!(UnstakerByStakeId::<Test>::contains_key(
  936. curator_role_stake_id
  937. ));
  938. let unstaker = UnstakerByStakeId::<Test>::get(curator_role_stake_id);
  939. assert_eq!(unstaker, WorkingGroupUnstaker::Curator(self.curator_id));
  940. /*
  941. * TODO: Missing checks to calls to
  942. * recurringrewards, stake
  943. */
  944. }
  945. }
  946. #[test]
  947. fn terminate_curator_role_success() {
  948. TestExternalitiesBuilder::<Test>::default()
  949. .build()
  950. .execute_with(|| {
  951. let result = setup_lead_and_hire_curator();
  952. let fixture = TerminateCuratorRoleFixture {
  953. origin: Origin::signed(LEAD_ROLE_ACCOUNT),
  954. curator_id: result.curator_id(),
  955. rationale_text: "This curator is a joke!".as_bytes().to_vec(),
  956. };
  957. fixture.call_and_assert_success();
  958. });
  959. }
  960. struct SetLeadFixture {
  961. pub origin: Origin,
  962. pub member_id: <Test as membership::Trait>::MemberId,
  963. pub new_role_account: <Test as system::Trait>::AccountId,
  964. }
  965. impl SetLeadFixture {
  966. fn call(&self) -> Result<(), &'static str> {
  967. ContentWorkingGroup::replace_lead(
  968. self.origin.clone(),
  969. Some((self.member_id, self.new_role_account)),
  970. )
  971. .map_err(<&str>::from)
  972. }
  973. pub fn call_and_assert_success(&self) {
  974. let original_next_lead_id = NextLeadId::<Test>::get();
  975. let call_result = self.call();
  976. assert_eq!(call_result, Ok(()));
  977. let updated_next_lead_id = NextLeadId::<Test>::get();
  978. assert_eq!(original_next_lead_id + 1, updated_next_lead_id);
  979. let new_lead_id = if let Some(id) = CurrentLeadId::<Test>::get() {
  980. id
  981. } else {
  982. panic!("Lead not set when it must be.")
  983. };
  984. let new_lead = LeadById::<Test>::get(new_lead_id);
  985. let expected_new_lead = Lead {
  986. member_id: self.member_id,
  987. role_account: self.new_role_account,
  988. reward_relationship: None,
  989. inducted: 1, // make dynamic later
  990. stage: LeadRoleState::Active,
  991. };
  992. assert_eq!(new_lead, expected_new_lead);
  993. assert_eq!(
  994. get_last_event_or_panic(),
  995. crate::RawEvent::LeadSet(new_lead_id)
  996. );
  997. }
  998. }
  999. #[test]
  1000. fn set_lead_success() {
  1001. TestExternalitiesBuilder::<Test>::default()
  1002. .build()
  1003. .execute_with(|| {
  1004. /*
  1005. Events are not emitted on block 0.
  1006. So any dispatchable calls made during genesis block formation will have no events emitted.
  1007. https://substrate.dev/recipes/2-appetizers/4-events.html
  1008. */
  1009. run_to_block(1);
  1010. let member_id =
  1011. add_member(LEAD_ROOT_AND_CONTROLLER_ACCOUNT, to_vec(LEAD_MEMBER_HANDLE));
  1012. SetLeadFixture {
  1013. origin: RawOrigin::Root.into(),
  1014. member_id,
  1015. new_role_account: 44444,
  1016. }
  1017. .call_and_assert_success();
  1018. });
  1019. }
  1020. struct UnsetLeadFixture {
  1021. pub origin: Origin,
  1022. }
  1023. impl UnsetLeadFixture {
  1024. fn call(&self) -> Result<(), &'static str> {
  1025. ContentWorkingGroup::replace_lead(self.origin.clone(), None).map_err(<&str>::from)
  1026. }
  1027. pub fn call_and_assert_success(&self) {
  1028. let original_lead_id = CurrentLeadId::<Test>::get().unwrap();
  1029. let original_lead = LeadById::<Test>::get(original_lead_id);
  1030. let call_result = self.call();
  1031. assert_eq!(call_result, Ok(()));
  1032. assert!(CurrentLeadId::<Test>::get().is_none());
  1033. let updated_lead = LeadById::<Test>::get(original_lead_id);
  1034. let expected_updated_lead = Lead {
  1035. stage: LeadRoleState::Exited(ExitedLeadRole {
  1036. initiated_at_block_number: 1,
  1037. }),
  1038. ..original_lead
  1039. };
  1040. assert_eq!(updated_lead, expected_updated_lead);
  1041. assert_eq!(
  1042. get_last_event_or_panic(),
  1043. crate::RawEvent::LeadUnset(original_lead_id)
  1044. );
  1045. }
  1046. }
  1047. #[test]
  1048. fn unset_lead_success() {
  1049. TestExternalitiesBuilder::<Test>::default()
  1050. .build()
  1051. .execute_with(|| {
  1052. let _ = add_member_and_set_as_lead();
  1053. UnsetLeadFixture {
  1054. origin: RawOrigin::Root.into(),
  1055. }
  1056. .call_and_assert_success();
  1057. });
  1058. }
  1059. struct UnstakedFixture {
  1060. pub stake_id: StakeId<Test>,
  1061. }
  1062. impl UnstakedFixture {
  1063. fn call(&self) {
  1064. ContentWorkingGroup::unstaked(self.stake_id);
  1065. }
  1066. pub fn call_and_assert_success(&self) {
  1067. let unstaker = UnstakerByStakeId::<Test>::get(self.stake_id);
  1068. let curator_id = if let WorkingGroupUnstaker::Curator(curator_id) = unstaker {
  1069. curator_id
  1070. } else {
  1071. panic!("Unstaker not curator")
  1072. };
  1073. let original_curator = CuratorById::<Test>::get(curator_id);
  1074. let original_exit_summary =
  1075. if let CuratorRoleStage::Unstaking(exit_summary) = (original_curator.clone()).stage {
  1076. exit_summary
  1077. } else {
  1078. panic!("Curator not unstaking")
  1079. };
  1080. self.call();
  1081. let expected_curator = Curator {
  1082. stage: CuratorRoleStage::Exited(original_exit_summary),
  1083. ..(original_curator.clone())
  1084. };
  1085. let updated_curator = CuratorById::<Test>::get(curator_id);
  1086. assert_eq!(updated_curator, expected_curator);
  1087. assert_eq!(
  1088. get_last_event_or_panic(),
  1089. crate::RawEvent::TerminatedCurator(curator_id)
  1090. );
  1091. // Unstaker gone
  1092. assert!(!UnstakerByStakeId::<Test>::contains_key(self.stake_id));
  1093. }
  1094. // pub fn call_and_assert_failed_result(&self, error_message: &'static str) {
  1095. // let call_result = self.call();
  1096. // assert_eq!(call_result, Err(error_message));
  1097. // }
  1098. }
  1099. #[test]
  1100. fn unstaked_curator_success() {
  1101. TestExternalitiesBuilder::<Test>::default()
  1102. .build()
  1103. .execute_with(|| {
  1104. let result = setup_lead_and_hire_curator();
  1105. TerminateCuratorRoleFixture {
  1106. origin: Origin::signed(LEAD_ROLE_ACCOUNT),
  1107. curator_id: result.curator_id(),
  1108. rationale_text: "This curator is a joke!".as_bytes().to_vec(),
  1109. }
  1110. .call_and_assert_success();
  1111. let curator_role_stake_id = CuratorById::<Test>::get(result.curator_id())
  1112. .role_stake_profile
  1113. .unwrap()
  1114. .stake_id;
  1115. UnstakedFixture {
  1116. stake_id: curator_role_stake_id,
  1117. }
  1118. .call_and_assert_success();
  1119. });
  1120. }
  1121. #[test]
  1122. fn account_can_act_as_principal_success() {}
  1123. /*
  1124. * Fixtures
  1125. */
  1126. static LEAD_ROOT_AND_CONTROLLER_ACCOUNT: <Test as system::Trait>::AccountId = 1289;
  1127. static LEAD_ROLE_ACCOUNT: <Test as system::Trait>::AccountId = 1289;
  1128. static LEAD_MEMBER_HANDLE: &str = "IamTheLead";
  1129. static CHANNEL_CREATOR_ROOT_AND_CONTROLLER_ACCOUNT: <Test as system::Trait>::AccountId = 11;
  1130. static CHANNEL_CREATOR_HANDLE: &str = "Coolcreator1";
  1131. static CHANNEL_CREATOR_HANDLE2: &str = "Coolcreator2";
  1132. fn make_generic_add_member_params() -> AddMemberAndApplyOnOpeningParams {
  1133. AddMemberAndApplyOnOpeningParams::new(
  1134. 2222,
  1135. to_vec("yoyoyo0"), // generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  1136. 2222 * 2,
  1137. generate_valid_length_buffer(&CuratorApplicationHumanReadableText::get()),
  1138. )
  1139. }
  1140. /// Made into function to avoid having to clone every time we read fields
  1141. pub fn get_baseline_opening_policy(
  1142. ) -> OpeningPolicyCommitment<<Test as system::Trait>::BlockNumber, BalanceOf<Test>> {
  1143. OpeningPolicyCommitment {
  1144. application_rationing_policy: Some(hiring::ApplicationRationingPolicy {
  1145. max_active_applicants: 5,
  1146. }),
  1147. max_review_period_length: 100,
  1148. application_staking_policy: Some(hiring::StakingPolicy {
  1149. amount: 40000,
  1150. amount_mode: hiring::StakingAmountLimitMode::Exact,
  1151. crowded_out_unstaking_period_length: Some(3),
  1152. review_period_expired_unstaking_period_length: Some(22),
  1153. }),
  1154. role_staking_policy: Some(hiring::StakingPolicy {
  1155. amount: 900000,
  1156. amount_mode: hiring::StakingAmountLimitMode::AtLeast,
  1157. crowded_out_unstaking_period_length: Some(30),
  1158. review_period_expired_unstaking_period_length: Some(2),
  1159. }),
  1160. role_slashing_terms: SlashingTerms::Unslashable,
  1161. fill_opening_successful_applicant_application_stake_unstaking_period: None,
  1162. fill_opening_failed_applicant_application_stake_unstaking_period: None,
  1163. fill_opening_failed_applicant_role_stake_unstaking_period: None,
  1164. terminate_curator_application_stake_unstaking_period: None,
  1165. terminate_curator_role_stake_unstaking_period: None,
  1166. exit_curator_role_application_stake_unstaking_period: None,
  1167. exit_curator_role_stake_unstaking_period: None,
  1168. }
  1169. }
  1170. pub fn to_vec(s: &str) -> Vec<u8> {
  1171. s.as_bytes().to_vec()
  1172. }
  1173. // MOVE THIS LATER WHEN fill_opening is factored out
  1174. #[derive(Clone)]
  1175. pub struct FillOpeningApplicantParams {
  1176. pub add_and_apply_params: AddMemberAndApplyOnOpeningParams,
  1177. pub hire: bool,
  1178. }
  1179. impl FillOpeningApplicantParams {
  1180. pub fn new(add_and_apply_params: AddMemberAndApplyOnOpeningParams, hire: bool) -> Self {
  1181. Self {
  1182. add_and_apply_params: add_and_apply_params.clone(),
  1183. hire: hire,
  1184. }
  1185. }
  1186. }
  1187. #[derive(Clone)]
  1188. pub struct AddMemberAndApplyOnOpeningParams {
  1189. pub curator_applicant_root_and_controller_account: <Test as system::Trait>::AccountId,
  1190. pub handle: Vec<u8>,
  1191. pub curator_applicant_role_account: <Test as system::Trait>::AccountId,
  1192. pub human_readable_text: Vec<u8>,
  1193. }
  1194. impl AddMemberAndApplyOnOpeningParams {
  1195. pub fn new(
  1196. curator_applicant_root_and_controller_account: <Test as system::Trait>::AccountId,
  1197. handle: Vec<u8>,
  1198. curator_applicant_role_account: <Test as system::Trait>::AccountId,
  1199. human_readable_text: Vec<u8>,
  1200. ) -> Self {
  1201. Self {
  1202. curator_applicant_root_and_controller_account,
  1203. handle,
  1204. curator_applicant_role_account,
  1205. human_readable_text,
  1206. }
  1207. }
  1208. }
  1209. fn add_members_and_apply_on_opening(
  1210. curator_opening_id: CuratorOpeningId<Test>,
  1211. applicants: &Vec<AddMemberAndApplyOnOpeningParams>,
  1212. ) -> Vec<NewMemberAppliedResult> {
  1213. applicants
  1214. .iter()
  1215. .cloned()
  1216. .map(|params| -> NewMemberAppliedResult {
  1217. add_member_and_apply_on_opening(
  1218. curator_opening_id,
  1219. params.curator_applicant_root_and_controller_account,
  1220. params.handle,
  1221. params.curator_applicant_role_account,
  1222. params.human_readable_text,
  1223. )
  1224. })
  1225. .collect()
  1226. }
  1227. #[derive(Clone)]
  1228. struct NewMemberAppliedResult {
  1229. pub member_id: <Test as membership::Trait>::MemberId,
  1230. pub curator_application_id: crate::CuratorApplicationId<Test>,
  1231. }
  1232. fn add_member_and_apply_on_opening(
  1233. curator_opening_id: CuratorOpeningId<Test>,
  1234. curator_applicant_root_and_controller_account: <Test as system::Trait>::AccountId,
  1235. handle: Vec<u8>,
  1236. curator_applicant_role_account: <Test as system::Trait>::AccountId,
  1237. human_readable_text: Vec<u8>,
  1238. ) -> NewMemberAppliedResult {
  1239. // Make membership
  1240. let curator_applicant_member_id =
  1241. add_member(curator_applicant_root_and_controller_account, handle);
  1242. // Guarantee sufficient stake
  1243. let role_stake_balance = if let Some(policy) = get_baseline_opening_policy().role_staking_policy
  1244. {
  1245. policy.amount
  1246. } else {
  1247. 0
  1248. };
  1249. let application_stake_balance =
  1250. if let Some(policy) = get_baseline_opening_policy().application_staking_policy {
  1251. policy.amount
  1252. } else {
  1253. 0
  1254. };
  1255. let total_balance = role_stake_balance + application_stake_balance;
  1256. let source_account = curator_applicant_root_and_controller_account;
  1257. // Credit staking source account if required
  1258. if total_balance > 0 {
  1259. let _ = balances::Module::<Test>::deposit_creating(&source_account, total_balance);
  1260. }
  1261. let expected_hiring_application_id = <hiring::NextApplicationId<Test>>::get();
  1262. let old_curator_opening = CuratorOpeningById::<Test>::get(curator_opening_id);
  1263. let new_curator_application_id = NextCuratorApplicationId::<Test>::get();
  1264. /*
  1265. * Test
  1266. */
  1267. assert_eq!(
  1268. ContentWorkingGroup::apply_on_curator_opening(
  1269. Origin::signed(curator_applicant_root_and_controller_account),
  1270. curator_applicant_member_id,
  1271. curator_opening_id,
  1272. curator_applicant_role_account,
  1273. Some(role_stake_balance),
  1274. Some(application_stake_balance),
  1275. human_readable_text
  1276. )
  1277. .unwrap(),
  1278. ()
  1279. );
  1280. assert_eq!(
  1281. get_last_event_or_panic(),
  1282. crate::RawEvent::AppliedOnCuratorOpening(curator_opening_id, new_curator_application_id)
  1283. );
  1284. assert!(CuratorApplicationById::<Test>::contains_key(
  1285. new_curator_application_id
  1286. ));
  1287. // Assert that appropriate application has been added
  1288. let new_curator_application = CuratorApplicationById::<Test>::get(new_curator_application_id);
  1289. let expected_curator_application = CuratorApplication {
  1290. role_account: curator_applicant_role_account,
  1291. curator_opening_id: curator_opening_id,
  1292. member_id: curator_applicant_member_id,
  1293. application_id: expected_hiring_application_id,
  1294. };
  1295. assert_eq!(expected_curator_application, new_curator_application);
  1296. // Assert that the opening has had the application added to application list
  1297. let mut singleton = BTreeSet::new(); // Unavoidable mutable, BTreeSet can only be populated this way.
  1298. singleton.insert(new_curator_application_id);
  1299. let new_curator_applications = old_curator_opening
  1300. .curator_applications
  1301. .union(&singleton)
  1302. .cloned()
  1303. .collect();
  1304. let expected_curator_opening = CuratorOpening {
  1305. curator_applications: new_curator_applications,
  1306. ..old_curator_opening
  1307. };
  1308. let new_curator_opening = CuratorOpeningById::<Test>::get(curator_opening_id);
  1309. assert_eq!(expected_curator_opening, new_curator_opening);
  1310. NewMemberAppliedResult {
  1311. member_id: curator_applicant_member_id,
  1312. curator_application_id: new_curator_application_id,
  1313. }
  1314. }
  1315. struct NormalOpeningConstructed {
  1316. pub curator_opening_id: CuratorOpeningId<Test>,
  1317. pub new_member_as_lead: NewMemberAsLead,
  1318. }
  1319. fn setup_normal_opening() -> NormalOpeningConstructed {
  1320. let new_member_as_lead = add_member_and_set_as_lead();
  1321. let expected_curator_opening_id = NextCuratorOpeningId::<Test>::get();
  1322. assert_eq!(
  1323. ContentWorkingGroup::add_curator_opening(
  1324. Origin::signed(LEAD_ROLE_ACCOUNT),
  1325. hiring::ActivateOpeningAt::ExactBlock(34),
  1326. get_baseline_opening_policy(),
  1327. generate_valid_length_buffer(&OpeningHumanReadableText::get())
  1328. )
  1329. .unwrap(),
  1330. ()
  1331. );
  1332. assert_eq!(
  1333. get_last_event_or_panic(),
  1334. crate::RawEvent::CuratorOpeningAdded(expected_curator_opening_id)
  1335. );
  1336. NormalOpeningConstructed {
  1337. curator_opening_id: expected_curator_opening_id,
  1338. new_member_as_lead,
  1339. }
  1340. }
  1341. fn setup_normal_accepting_opening() -> NormalOpeningConstructed {
  1342. let normal_opening_constructed = setup_normal_opening();
  1343. assert_eq!(
  1344. ContentWorkingGroup::accept_curator_applications(
  1345. Origin::signed(LEAD_ROLE_ACCOUNT), // <== get dynamic value from somewhere else later
  1346. normal_opening_constructed.curator_opening_id
  1347. )
  1348. .unwrap(),
  1349. ()
  1350. );
  1351. normal_opening_constructed
  1352. }
  1353. struct SetupOpeningInReview {
  1354. //pub curator_opening_id: lib::CuratorOpeningId<Test>,
  1355. pub normal_opening_constructed: NormalOpeningConstructed,
  1356. pub added_members_application_result: Vec<NewMemberAppliedResult>,
  1357. }
  1358. fn setup_opening_in_review(
  1359. applicants: &Vec<AddMemberAndApplyOnOpeningParams>,
  1360. ) -> SetupOpeningInReview {
  1361. let normal_opening_constructed = setup_normal_accepting_opening();
  1362. let added_members_application_result =
  1363. add_members_and_apply_on_opening(normal_opening_constructed.curator_opening_id, applicants);
  1364. assert_eq!(
  1365. ContentWorkingGroup::begin_curator_applicant_review(
  1366. Origin::signed(LEAD_ROLE_ACCOUNT),
  1367. normal_opening_constructed.curator_opening_id
  1368. )
  1369. .unwrap(),
  1370. ()
  1371. );
  1372. // TODO: assert event stuff !!!!
  1373. SetupOpeningInReview {
  1374. normal_opening_constructed,
  1375. added_members_application_result,
  1376. }
  1377. }
  1378. enum FillOpeningApplicantOutcome {
  1379. NotHired,
  1380. Hired { curator_id: CuratorId<Test> },
  1381. }
  1382. struct SetupAndFillOpeningResult {
  1383. setup_opening_in_review: SetupOpeningInReview,
  1384. application_outomes: Vec<FillOpeningApplicantOutcome>,
  1385. }
  1386. fn setup_and_fill_opening(
  1387. applicants: &Vec<FillOpeningApplicantParams>,
  1388. ) -> SetupAndFillOpeningResult {
  1389. let setup_opening_params = applicants
  1390. .iter()
  1391. .cloned()
  1392. .map(|param| param.add_and_apply_params)
  1393. .collect::<Vec<_>>();
  1394. let setup_opening_in_review = setup_opening_in_review(&setup_opening_params);
  1395. let curator_opening = CuratorOpeningById::<Test>::get(
  1396. setup_opening_in_review
  1397. .normal_opening_constructed
  1398. .curator_opening_id,
  1399. );
  1400. // Set whom to hire
  1401. let applicants_to_hire_iter = applicants.iter().filter(|params| params.hire);
  1402. let num_applicants_hired = applicants_to_hire_iter.cloned().count();
  1403. let hired_applicant_and_result = setup_opening_in_review
  1404. .added_members_application_result
  1405. .iter()
  1406. .zip(applicants.iter())
  1407. .filter(|(_, fill_opening_applicant_params)| fill_opening_applicant_params.hire)
  1408. .collect::<Vec<_>>();
  1409. let successful_curator_application_ids = hired_applicant_and_result
  1410. .iter()
  1411. .map(|(new_member_applied_result, _)| new_member_applied_result.curator_application_id)
  1412. .collect::<BTreeSet<_>>();
  1413. // Remember original id counters
  1414. let original_next_curator_id = NextCuratorId::<Test>::get();
  1415. let original_next_principal_id = NextPrincipalId::<Test>::get();
  1416. /*
  1417. * Call
  1418. */
  1419. assert_eq!(
  1420. ContentWorkingGroup::fill_curator_opening(
  1421. Origin::signed(LEAD_ROLE_ACCOUNT),
  1422. setup_opening_in_review
  1423. .normal_opening_constructed
  1424. .curator_opening_id,
  1425. successful_curator_application_ids.clone(),
  1426. None
  1427. ),
  1428. Ok(())
  1429. );
  1430. /*
  1431. * Asserts
  1432. */
  1433. let successful_curator_application_id_to_curator_id = successful_curator_application_ids
  1434. .iter()
  1435. .enumerate()
  1436. .map(
  1437. |(index, item)| -> (CuratorApplicationId<Test>, CuratorId<Test>) {
  1438. let curator_id = original_next_curator_id + (index as CuratorId<Test>);
  1439. (*item, curator_id)
  1440. },
  1441. )
  1442. .collect::<BTreeMap<_, _>>();
  1443. assert_eq!(
  1444. get_last_event_or_panic(),
  1445. crate::RawEvent::CuratorOpeningFilled(
  1446. setup_opening_in_review
  1447. .normal_opening_constructed
  1448. .curator_opening_id,
  1449. successful_curator_application_id_to_curator_id
  1450. )
  1451. );
  1452. // The right number of curators have been created
  1453. let num_curators_created = NextCuratorId::<Test>::get() - original_next_curator_id;
  1454. assert_eq!(num_curators_created, (num_applicants_hired as u64));
  1455. // The right numbe of prinipals were created
  1456. let num_principals_created = NextPrincipalId::<Test>::get() - original_next_principal_id;
  1457. assert_eq!(num_principals_created, (num_applicants_hired as u64));
  1458. // Inspect all expected curators and principal added
  1459. for (hired_index, item) in hired_applicant_and_result.iter().enumerate() {
  1460. let (new_member_applied_result, fill_opening_applicant_params) = item;
  1461. // Curator
  1462. let expected_added_curator_id: u64 = (hired_index as u64) + original_next_curator_id;
  1463. // Principal
  1464. let expected_added_principal_id: u64 = (hired_index as u64) + original_next_principal_id;
  1465. // Curator added
  1466. assert!(CuratorById::<Test>::contains_key(expected_added_curator_id));
  1467. let added_curator = CuratorById::<Test>::get(expected_added_curator_id);
  1468. // expected_curator
  1469. let reward_relationship = None::<<Test as recurringrewards::Trait>::RewardRelationshipId>;
  1470. let curator_application =
  1471. CuratorApplicationById::<Test>::get(new_member_applied_result.curator_application_id);
  1472. let application_id = curator_application.application_id;
  1473. let application = hiring::ApplicationById::<Test>::get(application_id);
  1474. let role_stake_profile = if let Some(ref stake_id) = application.active_role_staking_id {
  1475. // get_baseline_opening_policy().role_staking_policy {
  1476. Some(CuratorRoleStakeProfile::new(
  1477. stake_id,
  1478. &curator_opening
  1479. .policy_commitment
  1480. .terminate_curator_role_stake_unstaking_period,
  1481. &curator_opening
  1482. .policy_commitment
  1483. .exit_curator_role_stake_unstaking_period,
  1484. ))
  1485. } else {
  1486. None
  1487. };
  1488. let expected_curator = Curator {
  1489. role_account: fill_opening_applicant_params
  1490. .add_and_apply_params
  1491. .curator_applicant_role_account,
  1492. reward_relationship: reward_relationship,
  1493. role_stake_profile: role_stake_profile, // added_curator.role_stake_profile.clone(),
  1494. stage: CuratorRoleStage::Active,
  1495. induction: CuratorInduction::new(
  1496. &setup_opening_in_review
  1497. .normal_opening_constructed
  1498. .new_member_as_lead
  1499. .lead_id,
  1500. &new_member_applied_result.curator_application_id,
  1501. &1,
  1502. ),
  1503. principal_id: expected_added_principal_id,
  1504. };
  1505. assert_eq!(expected_curator, added_curator);
  1506. // Principal added
  1507. assert!(PrincipalById::<Test>::contains_key(
  1508. expected_added_principal_id
  1509. ));
  1510. let added_principal = PrincipalById::<Test>::get(expected_added_principal_id);
  1511. let expected_added_principal = Principal::Curator(expected_added_principal_id);
  1512. assert_eq!(added_principal, expected_added_principal);
  1513. }
  1514. /*
  1515. * TODO: add assertion abouot side-effect in !hiring & membership! module,
  1516. * this is where state of application has fundamentally changed.
  1517. */
  1518. let application_outomes = applicants
  1519. .iter()
  1520. .enumerate()
  1521. .map(|(index, params)| {
  1522. if params.hire {
  1523. FillOpeningApplicantOutcome::Hired {
  1524. curator_id: (index as u64) + original_next_curator_id,
  1525. }
  1526. } else {
  1527. FillOpeningApplicantOutcome::NotHired
  1528. }
  1529. })
  1530. .collect::<Vec<_>>();
  1531. SetupAndFillOpeningResult {
  1532. setup_opening_in_review,
  1533. application_outomes,
  1534. }
  1535. }
  1536. struct SetupLeadAndHireCuratorResult {
  1537. pub curator_params: AddMemberAndApplyOnOpeningParams,
  1538. pub setup_and_fill_opening_result: SetupAndFillOpeningResult,
  1539. }
  1540. impl SetupLeadAndHireCuratorResult {
  1541. fn curator_params(&self) -> AddMemberAndApplyOnOpeningParams {
  1542. self.curator_params.clone()
  1543. }
  1544. pub fn curator_id(&self) -> CuratorId<Test> {
  1545. match self.setup_and_fill_opening_result.application_outomes[0] {
  1546. FillOpeningApplicantOutcome::Hired { curator_id } => curator_id,
  1547. _ => panic!(),
  1548. }
  1549. }
  1550. pub fn curator_member_id(&self) -> <Test as membership::Trait>::MemberId {
  1551. self.setup_and_fill_opening_result
  1552. .setup_opening_in_review
  1553. .added_members_application_result[0]
  1554. .member_id
  1555. }
  1556. }
  1557. fn setup_lead_and_hire_curator() -> SetupLeadAndHireCuratorResult {
  1558. let curator_params = make_generic_add_member_params();
  1559. // Hire curator
  1560. let setup_and_fill_opening_result =
  1561. setup_and_fill_opening(&vec![FillOpeningApplicantParams::new(
  1562. curator_params.clone(),
  1563. true,
  1564. )]);
  1565. SetupLeadAndHireCuratorResult {
  1566. curator_params,
  1567. setup_and_fill_opening_result,
  1568. }
  1569. }
  1570. struct CreateChannelFixture {
  1571. pub channel_creator_member_id: <Test as membership::Trait>::MemberId,
  1572. pub controller_account: <Test as system::Trait>::AccountId,
  1573. pub channel_creator_role_account: <Test as system::Trait>::AccountId,
  1574. pub channel_handle: Vec<u8>,
  1575. pub channel_title: OptionalText,
  1576. pub description: OptionalText,
  1577. pub avatar: OptionalText,
  1578. pub banner: OptionalText,
  1579. pub content: ChannelContentType,
  1580. pub publication_status: ChannelPublicationStatus,
  1581. }
  1582. impl CreateChannelFixture {
  1583. pub fn make_valid_unpulished_video_channel_for(
  1584. channel_creator_member_id: <Test as membership::Trait>::MemberId,
  1585. override_controller_account: Option<<Test as system::Trait>::AccountId>,
  1586. ) -> Self {
  1587. let controller_account = if let Some(account) = override_controller_account {
  1588. account
  1589. } else {
  1590. membership::Module::<Test>::ensure_membership(channel_creator_member_id)
  1591. .unwrap()
  1592. .controller_account
  1593. };
  1594. Self {
  1595. channel_creator_member_id,
  1596. controller_account,
  1597. channel_creator_role_account: 527489,
  1598. channel_handle: generate_valid_length_buffer(&ChannelHandleConstraint::get()),
  1599. channel_title: Some(generate_valid_length_buffer(&ChannelTitleConstraint::get())),
  1600. avatar: Some(generate_valid_length_buffer(&ChannelAvatarConstraint::get())),
  1601. banner: Some(generate_valid_length_buffer(&ChannelBannerConstraint::get())),
  1602. description: Some(generate_valid_length_buffer(
  1603. &ChannelDescriptionConstraint::get(),
  1604. )),
  1605. content: ChannelContentType::Video,
  1606. publication_status: ChannelPublicationStatus::Unlisted,
  1607. }
  1608. }
  1609. fn create_channel(&self) -> Result<(), &'static str> {
  1610. ContentWorkingGroup::create_channel(
  1611. Origin::signed(self.controller_account),
  1612. self.channel_creator_member_id,
  1613. self.channel_creator_role_account,
  1614. self.content.clone(),
  1615. self.channel_handle.clone(),
  1616. self.channel_title.clone(),
  1617. self.description.clone(),
  1618. self.avatar.clone(),
  1619. self.banner.clone(),
  1620. self.publication_status.clone(),
  1621. )
  1622. .map_err(<&str>::from)
  1623. }
  1624. pub fn call_and_assert_error(&self, err_message: &'static str) {
  1625. let number_of_events_before_call = System::events().len();
  1626. let call_result = self.create_channel();
  1627. assert_eq!(call_result, Err(err_message));
  1628. // No new events deposited
  1629. assert_eq!(System::events().len(), number_of_events_before_call);
  1630. }
  1631. pub fn call_and_assert_success(&self) -> ChannelId<Test> {
  1632. let old_next_channel_id = NextChannelId::<Test>::get();
  1633. let call_result = self.create_channel();
  1634. // Call result was Ok
  1635. assert_eq!(call_result, Ok(()));
  1636. // Assert that event was triggered,
  1637. // keep channel id.
  1638. assert_eq!(
  1639. get_last_event_or_panic(),
  1640. crate::RawEvent::ChannelCreated(old_next_channel_id)
  1641. );
  1642. let channel_id = old_next_channel_id;
  1643. // Assert that given channel id has been added,
  1644. // and has the right properties.
  1645. assert!(crate::ChannelById::<Test>::contains_key(channel_id));
  1646. let created_channel = crate::ChannelById::<Test>::get(channel_id);
  1647. let expected_channel = Channel {
  1648. verified: false,
  1649. handle: self.channel_handle.clone(),
  1650. title: self.channel_title.clone(),
  1651. avatar: self.avatar.clone(),
  1652. banner: self.banner.clone(),
  1653. description: self.description.clone(),
  1654. content: self.content.clone(),
  1655. owner: self.channel_creator_member_id,
  1656. role_account: self.channel_creator_role_account,
  1657. publication_status: self.publication_status.clone(),
  1658. curation_status: ChannelCurationStatus::Normal,
  1659. created: 1, // <== replace with now()
  1660. // We have no expectation here, so we just copy what was added
  1661. principal_id: created_channel.principal_id,
  1662. };
  1663. assert_eq!(created_channel, expected_channel);
  1664. // Assert that next id incremented.
  1665. assert_eq!(crate::NextChannelId::<Test>::get(), channel_id + 1);
  1666. // Assert that there is a mapping established for handle
  1667. assert_eq!(
  1668. crate::ChannelIdByHandle::<Test>::get(self.channel_handle.clone()),
  1669. channel_id
  1670. );
  1671. // Check that principal actually has been added
  1672. assert!(crate::PrincipalById::<Test>::contains_key(
  1673. created_channel.principal_id
  1674. ));
  1675. let created_principal = crate::PrincipalById::<Test>::get(created_channel.principal_id);
  1676. assert!(match created_principal {
  1677. Principal::Lead => false,
  1678. Principal::Curator(_) => false,
  1679. Principal::ChannelOwner(created_principal_channel_id) =>
  1680. created_principal_channel_id == channel_id,
  1681. });
  1682. channel_id
  1683. }
  1684. }
  1685. struct NewMemberAsLead {
  1686. pub member_id: <Test as membership::Trait>::MemberId,
  1687. pub lead_id: LeadId<Test>,
  1688. }
  1689. fn add_member_and_set_as_lead() -> NewMemberAsLead {
  1690. let member_id = add_member(LEAD_ROOT_AND_CONTROLLER_ACCOUNT, to_vec(LEAD_MEMBER_HANDLE));
  1691. let lead_id = set_lead(member_id, LEAD_ROLE_ACCOUNT);
  1692. NewMemberAsLead { member_id, lead_id }
  1693. }
  1694. pub fn set_channel_creation_enabled(enabled: bool) {
  1695. crate::Module::<Test>::set_channel_creation_enabled(Origin::signed(LEAD_ROLE_ACCOUNT), enabled)
  1696. .unwrap()
  1697. }
  1698. pub fn add_channel_creator_member() -> <Test as membership::Trait>::MemberId {
  1699. let channel_creator_member_id = add_member(
  1700. CHANNEL_CREATOR_ROOT_AND_CONTROLLER_ACCOUNT,
  1701. to_vec(CHANNEL_CREATOR_HANDLE),
  1702. );
  1703. channel_creator_member_id
  1704. }
  1705. pub fn add_member(
  1706. root_and_controller_account: <Test as system::Trait>::AccountId,
  1707. handle: Vec<u8>,
  1708. ) -> <Test as membership::Trait>::MemberId {
  1709. let next_member_id = membership::NextMemberId::<Test>::get();
  1710. assert_eq!(
  1711. membership::Module::<Test>::buy_membership(
  1712. Origin::signed(root_and_controller_account),
  1713. 0,
  1714. Some(handle),
  1715. None,
  1716. None
  1717. )
  1718. .unwrap(),
  1719. ()
  1720. );
  1721. next_member_id
  1722. }
  1723. pub fn set_lead(
  1724. member_id: <Test as membership::Trait>::MemberId,
  1725. new_role_account: <Test as system::Trait>::AccountId,
  1726. ) -> LeadId<Test> {
  1727. /*
  1728. Events are not emitted on block 0.
  1729. So any dispatchable calls made during genesis block formation will have no events emitted.
  1730. https://substrate.dev/recipes/2-appetizers/4-events.html
  1731. */
  1732. run_to_block(1);
  1733. let expected_lead_id = NextLeadId::<Test>::get();
  1734. // Set lead
  1735. assert_eq!(
  1736. ContentWorkingGroup::replace_lead(
  1737. RawOrigin::Root.into(),
  1738. Some((member_id, new_role_account))
  1739. )
  1740. .unwrap(),
  1741. ()
  1742. );
  1743. assert_eq!(
  1744. get_last_event_or_panic(),
  1745. crate::RawEvent::LeadSet(expected_lead_id)
  1746. );
  1747. expected_lead_id
  1748. }
  1749. pub fn add_curator_opening() -> CuratorOpeningId<Test> {
  1750. let activate_at = hiring::ActivateOpeningAt::ExactBlock(34);
  1751. let human_readable_text = generate_valid_length_buffer(&OpeningHumanReadableText::get());
  1752. let expected_curator_opening_id = NextCuratorOpeningId::<Test>::get();
  1753. assert_eq!(
  1754. ContentWorkingGroup::add_curator_opening(
  1755. Origin::signed(LEAD_ROLE_ACCOUNT),
  1756. activate_at.clone(),
  1757. get_baseline_opening_policy(),
  1758. human_readable_text.clone()
  1759. )
  1760. .unwrap(),
  1761. ()
  1762. );
  1763. assert_eq!(
  1764. get_last_event_or_panic(),
  1765. crate::RawEvent::CuratorOpeningAdded(expected_curator_opening_id)
  1766. );
  1767. expected_curator_opening_id
  1768. }
  1769. /*
  1770. * Buffer generators
  1771. */
  1772. pub fn generate_text(len: usize) -> Vec<u8> {
  1773. vec![b'x'; len]
  1774. }
  1775. pub fn generate_valid_length_buffer(constraint: &InputValidationLengthConstraint) -> Vec<u8> {
  1776. generate_text(constraint.min as usize)
  1777. }
  1778. pub fn generate_too_short_length_buffer(constraint: &InputValidationLengthConstraint) -> Vec<u8> {
  1779. generate_text((constraint.min - 1) as usize)
  1780. }
  1781. pub fn generate_too_long_length_buffer(constraint: &InputValidationLengthConstraint) -> Vec<u8> {
  1782. generate_text((constraint.max() + 1) as usize)
  1783. }
  1784. #[test]
  1785. fn increasing_mint_capacity() {
  1786. const MINT_CAPACITY: u64 = 50000;
  1787. TestExternalitiesBuilder::<Test>::default()
  1788. .with_content_wg_config(
  1789. genesis::GenesisConfigBuilder::<Test>::default()
  1790. .with_mint_capacity(MINT_CAPACITY)
  1791. .build(),
  1792. )
  1793. .build()
  1794. .execute_with(|| {
  1795. /*
  1796. Events are not emitted on block 0.
  1797. So any dispatchable calls made during genesis block formation will have no events emitted.
  1798. https://substrate.dev/recipes/2-appetizers/4-events.html
  1799. */
  1800. run_to_block(1);
  1801. let mint_id = ContentWorkingGroup::mint();
  1802. let mint = Minting::mints(mint_id);
  1803. assert_eq!(mint.capacity(), MINT_CAPACITY);
  1804. let increase = 25000;
  1805. // Increasing mint capacity
  1806. let expected_new_capacity = MINT_CAPACITY + increase;
  1807. assert_ok!(ContentWorkingGroup::increase_mint_capacity(
  1808. RawOrigin::Root.into(),
  1809. increase
  1810. ));
  1811. // Excpected event after increasing
  1812. assert_eq!(
  1813. get_last_event_or_panic(),
  1814. crate::RawEvent::MintCapacityIncreased(mint_id, increase, expected_new_capacity)
  1815. );
  1816. // Excpected value of capacity after increasing
  1817. let mint = Minting::mints(mint_id);
  1818. assert_eq!(mint.capacity(), expected_new_capacity);
  1819. });
  1820. }
  1821. #[test]
  1822. fn setting_mint_capacity() {
  1823. const MINT_CAPACITY: u64 = 50000;
  1824. TestExternalitiesBuilder::<Test>::default()
  1825. .with_content_wg_config(
  1826. genesis::GenesisConfigBuilder::<Test>::default()
  1827. .with_mint_capacity(MINT_CAPACITY)
  1828. .build(),
  1829. )
  1830. .build()
  1831. .execute_with(|| {
  1832. /*
  1833. Events are not emitted on block 0.
  1834. So any dispatchable calls made during genesis block formation will have no events emitted.
  1835. https://substrate.dev/recipes/2-appetizers/4-events.html
  1836. */
  1837. run_to_block(1);
  1838. let mint_id = ContentWorkingGroup::mint();
  1839. let mint = Minting::mints(mint_id);
  1840. assert_eq!(mint.capacity(), MINT_CAPACITY);
  1841. // Decreasing mint capacity
  1842. let new_lower_capacity = 10000;
  1843. let decrease = MINT_CAPACITY - new_lower_capacity;
  1844. assert_ok!(ContentWorkingGroup::set_mint_capacity(
  1845. RawOrigin::Root.into(),
  1846. new_lower_capacity
  1847. ));
  1848. // Correct event after decreasing
  1849. assert_eq!(
  1850. get_last_event_or_panic(),
  1851. crate::RawEvent::MintCapacityDecreased(mint_id, decrease, new_lower_capacity)
  1852. );
  1853. // Correct value of capacity after decreasing
  1854. let mint = Minting::mints(mint_id);
  1855. assert_eq!(mint.capacity(), new_lower_capacity);
  1856. // Increasing mint capacity
  1857. let new_higher_capacity = 25000;
  1858. let increase = new_higher_capacity - mint.capacity();
  1859. assert_ok!(ContentWorkingGroup::set_mint_capacity(
  1860. RawOrigin::Root.into(),
  1861. new_higher_capacity
  1862. ));
  1863. // Excpected event after increasing
  1864. assert_eq!(
  1865. get_last_event_or_panic(),
  1866. crate::RawEvent::MintCapacityIncreased(mint_id, increase, new_higher_capacity)
  1867. );
  1868. // Excpected value of capacity after increasing
  1869. let mint = Minting::mints(mint_id);
  1870. assert_eq!(mint.capacity(), new_higher_capacity);
  1871. });
  1872. }