fuzzing.rs 12 KB

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