fuzzing.rs 12 KB

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