fuzzing.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. use dioxus::prelude::Props;
  2. use dioxus_core::*;
  3. use std::{cell::Cell, collections::HashSet};
  4. fn random_ns() -> Option<&'static str> {
  5. let namespace = rand::random::<u8>() % 2;
  6. match namespace {
  7. 0 => None,
  8. 1 => Some(Box::leak(
  9. format!("ns{}", rand::random::<usize>()).into_boxed_str(),
  10. )),
  11. _ => unreachable!(),
  12. }
  13. }
  14. fn create_random_attribute(attr_idx: &mut usize) -> TemplateAttribute<'static> {
  15. match rand::random::<u8>() % 2 {
  16. 0 => TemplateAttribute::Static {
  17. name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  18. value: Box::leak(format!("value{}", rand::random::<usize>()).into_boxed_str()),
  19. namespace: random_ns(),
  20. },
  21. 1 => TemplateAttribute::Dynamic {
  22. id: {
  23. let old_idx = *attr_idx;
  24. *attr_idx += 1;
  25. old_idx
  26. },
  27. },
  28. _ => unreachable!(),
  29. }
  30. }
  31. fn create_random_template_node(
  32. dynamic_node_types: &mut Vec<DynamicNodeType>,
  33. template_idx: &mut usize,
  34. attr_idx: &mut usize,
  35. depth: usize,
  36. ) -> TemplateNode<'static> {
  37. match rand::random::<u8>() % 4 {
  38. 0 => {
  39. let attrs = {
  40. let attrs: Vec<_> = (0..(rand::random::<usize>() % 10))
  41. .map(|_| create_random_attribute(attr_idx))
  42. .collect();
  43. Box::leak(attrs.into_boxed_slice())
  44. };
  45. TemplateNode::Element {
  46. tag: Box::leak(format!("tag{}", rand::random::<usize>()).into_boxed_str()),
  47. namespace: random_ns(),
  48. attrs,
  49. children: {
  50. if depth > 4 {
  51. &[]
  52. } else {
  53. let children: Vec<_> = (0..(rand::random::<usize>() % 3))
  54. .map(|_| {
  55. create_random_template_node(
  56. dynamic_node_types,
  57. template_idx,
  58. attr_idx,
  59. depth + 1,
  60. )
  61. })
  62. .collect();
  63. Box::leak(children.into_boxed_slice())
  64. }
  65. },
  66. }
  67. }
  68. 1 => TemplateNode::Text {
  69. text: Box::leak(format!("{}", rand::random::<usize>()).into_boxed_str()),
  70. },
  71. 2 => TemplateNode::DynamicText {
  72. id: {
  73. let old_idx = *template_idx;
  74. *template_idx += 1;
  75. dynamic_node_types.push(DynamicNodeType::Text);
  76. old_idx
  77. },
  78. },
  79. 3 => TemplateNode::Dynamic {
  80. id: {
  81. let old_idx = *template_idx;
  82. *template_idx += 1;
  83. dynamic_node_types.push(DynamicNodeType::Other);
  84. old_idx
  85. },
  86. },
  87. _ => unreachable!(),
  88. }
  89. }
  90. fn generate_paths(
  91. node: &TemplateNode<'static>,
  92. current_path: &[u8],
  93. node_paths: &mut Vec<Vec<u8>>,
  94. attr_paths: &mut Vec<Vec<u8>>,
  95. ) {
  96. match node {
  97. TemplateNode::Element { children, attrs, .. } => {
  98. for attr in *attrs {
  99. match attr {
  100. TemplateAttribute::Static { .. } => {}
  101. TemplateAttribute::Dynamic { .. } => {
  102. attr_paths.push(current_path.to_vec());
  103. }
  104. }
  105. }
  106. for (i, child) in children.iter().enumerate() {
  107. let mut current_path = current_path.to_vec();
  108. current_path.push(i as u8);
  109. generate_paths(child, &current_path, node_paths, attr_paths);
  110. }
  111. }
  112. TemplateNode::Text { .. } => {}
  113. TemplateNode::DynamicText { .. } => {
  114. node_paths.push(current_path.to_vec());
  115. }
  116. TemplateNode::Dynamic { .. } => {
  117. node_paths.push(current_path.to_vec());
  118. }
  119. }
  120. }
  121. enum DynamicNodeType {
  122. Text,
  123. Other,
  124. }
  125. fn create_random_template(name: &'static str) -> (Template<'static>, Vec<DynamicNodeType>) {
  126. let mut dynamic_node_type = Vec::new();
  127. let mut template_idx = 0;
  128. let mut attr_idx = 0;
  129. let roots = (0..(1 + rand::random::<usize>() % 5))
  130. .map(|_| {
  131. create_random_template_node(&mut dynamic_node_type, &mut template_idx, &mut attr_idx, 0)
  132. })
  133. .collect::<Vec<_>>();
  134. assert!(!roots.is_empty());
  135. let roots = Box::leak(roots.into_boxed_slice());
  136. let mut node_paths = Vec::new();
  137. let mut attr_paths = Vec::new();
  138. for (i, root) in roots.iter().enumerate() {
  139. generate_paths(root, &[i as u8], &mut node_paths, &mut attr_paths);
  140. }
  141. let node_paths = Box::leak(
  142. node_paths
  143. .into_iter()
  144. .map(|v| &*Box::leak(v.into_boxed_slice()))
  145. .collect::<Vec<_>>()
  146. .into_boxed_slice(),
  147. );
  148. let attr_paths = Box::leak(
  149. attr_paths
  150. .into_iter()
  151. .map(|v| &*Box::leak(v.into_boxed_slice()))
  152. .collect::<Vec<_>>()
  153. .into_boxed_slice(),
  154. );
  155. (
  156. Template { name, roots, node_paths, attr_paths },
  157. dynamic_node_type,
  158. )
  159. }
  160. fn create_random_dynamic_node(cx: &ScopeState, depth: usize) -> DynamicNode {
  161. let range = if depth > 5 { 1 } else { 4 };
  162. match rand::random::<u8>() % range {
  163. 0 => DynamicNode::Placeholder(Default::default()),
  164. 1 => cx.make_node((0..(rand::random::<u8>() % 5)).map(|_| VNode {
  165. key: None,
  166. parent: Default::default(),
  167. template: Cell::new(Template {
  168. name: concat!(file!(), ":", line!(), ":", column!(), ":0"),
  169. roots: &[TemplateNode::Dynamic { id: 0 }],
  170. node_paths: &[&[0]],
  171. attr_paths: &[],
  172. }),
  173. root_ids: Default::default(),
  174. dynamic_nodes: cx.bump().alloc([cx.component(
  175. create_random_element,
  176. DepthProps { depth, root: false },
  177. "create_random_element",
  178. )]),
  179. dynamic_attrs: &[],
  180. })),
  181. 2 => cx.component(
  182. create_random_element,
  183. DepthProps { depth, root: false },
  184. "create_random_element",
  185. ),
  186. 3 => {
  187. let data = String::from("borrowed data");
  188. let bumpped = cx.bump().alloc(data);
  189. cx.component(
  190. create_random_element_borrowed,
  191. BorrowedDepthProps { borrow: &*bumpped, inner: DepthProps { depth, root: false } },
  192. "create_random_element_borrowed",
  193. )
  194. }
  195. _ => unreachable!(),
  196. }
  197. }
  198. fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
  199. let value = match rand::random::<u8>() % 7 {
  200. 0 => AttributeValue::Text(Box::leak(
  201. format!("{}", rand::random::<usize>()).into_boxed_str(),
  202. )),
  203. 1 => AttributeValue::Float(rand::random()),
  204. 2 => AttributeValue::Int(rand::random()),
  205. 3 => AttributeValue::Bool(rand::random()),
  206. 4 => cx.any_value(rand::random::<usize>()),
  207. 5 => AttributeValue::None,
  208. 6 => {
  209. let value = cx.listener(|e: Event<String>| println!("{:?}", e));
  210. return Attribute {
  211. name: "ondata",
  212. value,
  213. namespace: None,
  214. mounted_element: Default::default(),
  215. volatile: false,
  216. };
  217. }
  218. _ => unreachable!(),
  219. };
  220. Attribute {
  221. name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  222. value,
  223. namespace: random_ns(),
  224. mounted_element: Default::default(),
  225. volatile: rand::random(),
  226. }
  227. }
  228. static mut TEMPLATE_COUNT: usize = 0;
  229. #[derive(Props)]
  230. struct BorrowedDepthProps<'a> {
  231. borrow: &'a str,
  232. inner: DepthProps,
  233. }
  234. fn create_random_element_borrowed<'a>(cx: Scope<'a, BorrowedDepthProps<'a>>) -> Element<'a> {
  235. println!("{}", cx.props.borrow);
  236. let bump = cx.bump();
  237. let allocated = bump.alloc(Scoped { scope: cx, props: &cx.props.inner });
  238. create_random_element(allocated)
  239. }
  240. #[derive(PartialEq, Props)]
  241. struct DepthProps {
  242. depth: usize,
  243. root: bool,
  244. }
  245. fn create_random_element(cx: Scope<DepthProps>) -> Element {
  246. if rand::random::<usize>() % 10 == 0 {
  247. cx.needs_update();
  248. }
  249. let range = if cx.props.root { 2 } else { 3 };
  250. let node = match rand::random::<usize>() % range {
  251. 0 | 1 => {
  252. let (template, dynamic_node_types) = create_random_template(Box::leak(
  253. format!(
  254. "{}{}",
  255. concat!(file!(), ":", line!(), ":", column!(), ":"),
  256. {
  257. unsafe {
  258. let old = TEMPLATE_COUNT;
  259. TEMPLATE_COUNT += 1;
  260. old
  261. }
  262. }
  263. )
  264. .into_boxed_str(),
  265. ));
  266. // println!("{template:#?}");
  267. let node = VNode {
  268. key: None,
  269. parent: None,
  270. template: Cell::new(template),
  271. root_ids: Default::default(),
  272. dynamic_nodes: {
  273. let dynamic_nodes: Vec<_> = dynamic_node_types
  274. .iter()
  275. .map(|ty| match ty {
  276. DynamicNodeType::Text => DynamicNode::Text(VText {
  277. value: Box::leak(
  278. format!("{}", rand::random::<usize>()).into_boxed_str(),
  279. ),
  280. id: Default::default(),
  281. }),
  282. DynamicNodeType::Other => {
  283. create_random_dynamic_node(cx, cx.props.depth + 1)
  284. }
  285. })
  286. .collect();
  287. cx.bump().alloc(dynamic_nodes)
  288. },
  289. dynamic_attrs: cx.bump().alloc(
  290. (0..template.attr_paths.len())
  291. .map(|_| create_random_dynamic_attr(cx))
  292. .collect::<Vec<_>>(),
  293. ),
  294. };
  295. Some(node)
  296. }
  297. _ => None,
  298. };
  299. // println!("{node:#?}");
  300. node
  301. }
  302. // test for panics when creating random nodes and templates
  303. #[test]
  304. fn create() {
  305. for _ in 0..1000 {
  306. let mut vdom =
  307. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  308. let _ = vdom.rebuild();
  309. }
  310. }
  311. // test for panics when diffing random nodes
  312. // This test will change the template every render which is not very realistic, but it helps stress the system
  313. #[test]
  314. fn diff() {
  315. for _ in 0..100000 {
  316. let mut vdom =
  317. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  318. let _ = vdom.rebuild();
  319. // A list of all elements that have had event listeners
  320. // This is intentionally never cleared, so that we can test that calling event listeners that are removed doesn't cause a panic
  321. let mut event_listeners = HashSet::new();
  322. for _ in 0..100 {
  323. for &id in &event_listeners {
  324. println!("firing event on {:?}", id);
  325. vdom.handle_event(
  326. "data",
  327. std::rc::Rc::new(String::from("hello world")),
  328. id,
  329. true,
  330. );
  331. }
  332. {
  333. let muts = vdom.render_immediate();
  334. for mut_ in muts.edits {
  335. if let Mutation::NewEventListener { name, id } = mut_ {
  336. println!("new event listener on {:?} for {:?}", id, name);
  337. event_listeners.insert(id);
  338. }
  339. }
  340. }
  341. }
  342. }
  343. }