fuzzing.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. #![cfg(not(miri))]
  2. use dioxus::prelude::*;
  3. use dioxus_core::{
  4. prelude::EventHandler, AttributeValue, DynamicNode, NoOpMutations, VComponent, VNode, *,
  5. };
  6. use std::{cfg, collections::HashSet, default::Default};
  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::DynamicText {
  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::DynamicText { .. } => {
  117. node_paths.push(current_path.to_vec());
  118. }
  119. TemplateNode::Dynamic { .. } => {
  120. node_paths.push(current_path.to_vec());
  121. }
  122. }
  123. }
  124. enum DynamicNodeType {
  125. Text,
  126. Other,
  127. }
  128. fn create_random_template(name: &'static str) -> (Template, Vec<DynamicNodeType>) {
  129. let mut dynamic_node_type = Vec::new();
  130. let mut template_idx = 0;
  131. let mut attr_idx = 0;
  132. let roots = (0..(1 + rand::random::<usize>() % 5))
  133. .map(|_| {
  134. create_random_template_node(&mut dynamic_node_type, &mut template_idx, &mut attr_idx, 0)
  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. (
  159. Template { name, roots, node_paths, attr_paths },
  160. dynamic_node_type,
  161. )
  162. }
  163. fn create_random_dynamic_node(depth: usize) -> DynamicNode {
  164. let range = if depth > 5 { 1 } else { 3 };
  165. match rand::random::<u8>() % range {
  166. 0 => DynamicNode::Placeholder(Default::default()),
  167. 1 => (0..(rand::random::<u8>() % 5))
  168. .map(|_| {
  169. VNode::new(
  170. None,
  171. Template {
  172. name: create_template_location(),
  173. roots: &[TemplateNode::Dynamic { id: 0 }],
  174. node_paths: &[&[0]],
  175. attr_paths: &[],
  176. },
  177. Box::new([DynamicNode::Component(VComponent::new(
  178. create_random_element,
  179. DepthProps { depth, root: false },
  180. "create_random_element",
  181. ))]),
  182. Box::new([]),
  183. )
  184. })
  185. .into_dyn_node(),
  186. 2 => DynamicNode::Component(VComponent::new(
  187. create_random_element,
  188. DepthProps { depth, root: false },
  189. "create_random_element",
  190. )),
  191. _ => unreachable!(),
  192. }
  193. }
  194. fn create_random_dynamic_attr() -> Attribute {
  195. let value = match rand::random::<u8>() % 7 {
  196. 0 => AttributeValue::Text(format!("{}", rand::random::<usize>())),
  197. 1 => AttributeValue::Float(rand::random()),
  198. 2 => AttributeValue::Int(rand::random()),
  199. 3 => AttributeValue::Bool(rand::random()),
  200. 4 => AttributeValue::any_value(rand::random::<usize>()),
  201. 5 => AttributeValue::None,
  202. 6 => {
  203. let value = AttributeValue::listener(|e: Event<String>| println!("{:?}", e));
  204. return Attribute::new("ondata", value, None, false);
  205. }
  206. _ => unreachable!(),
  207. };
  208. Attribute::new(
  209. Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  210. value,
  211. random_ns(),
  212. rand::random(),
  213. )
  214. .into()
  215. }
  216. static mut TEMPLATE_COUNT: usize = 0;
  217. fn create_template_location() -> &'static str {
  218. Box::leak(
  219. format!(
  220. "{}{}",
  221. concat!(file!(), ":", line!(), ":", column!(), ":"),
  222. {
  223. unsafe {
  224. let old = TEMPLATE_COUNT;
  225. TEMPLATE_COUNT += 1;
  226. old
  227. }
  228. }
  229. )
  230. .into_boxed_str(),
  231. )
  232. }
  233. #[derive(PartialEq, Props, Clone)]
  234. struct DepthProps {
  235. depth: usize,
  236. root: bool,
  237. }
  238. fn create_random_element(cx: DepthProps) -> Element {
  239. if rand::random::<usize>() % 10 == 0 {
  240. needs_update();
  241. }
  242. let range = if cx.root { 2 } else { 3 };
  243. let node = match rand::random::<usize>() % range {
  244. 0 | 1 => {
  245. let (template, dynamic_node_types) = create_random_template(create_template_location());
  246. let node = VNode::new(
  247. None,
  248. template,
  249. dynamic_node_types
  250. .iter()
  251. .map(|ty| match ty {
  252. DynamicNodeType::Text => {
  253. DynamicNode::Text(VText::new(format!("{}", rand::random::<usize>())))
  254. }
  255. DynamicNodeType::Other => create_random_dynamic_node(cx.depth + 1),
  256. })
  257. .collect(),
  258. (0..template.attr_paths.len())
  259. .map(|_| Box::new([create_random_dynamic_attr()]) as Box<[Attribute]>)
  260. .collect(),
  261. );
  262. Some(node)
  263. }
  264. _ => None,
  265. };
  266. // println!("{node:#?}");
  267. node
  268. }
  269. // test for panics when creating random nodes and templates
  270. #[test]
  271. fn create() {
  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. }
  278. }
  279. // test for panics when diffing random nodes
  280. // This test will change the template every render which is not very realistic, but it helps stress the system
  281. #[test]
  282. fn diff() {
  283. let repeat_count = if cfg!(miri) { 100 } else { 1000 };
  284. for _ in 0..repeat_count {
  285. let mut vdom =
  286. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  287. vdom.rebuild(&mut NoOpMutations);
  288. // A list of all elements that have had event listeners
  289. // This is intentionally never cleared, so that we can test that calling event listeners that are removed doesn't cause a panic
  290. let mut event_listeners = HashSet::new();
  291. for _ in 0..100 {
  292. for &id in &event_listeners {
  293. println!("firing event on {:?}", id);
  294. vdom.handle_event(
  295. "data",
  296. std::rc::Rc::new(String::from("hello world")),
  297. id,
  298. true,
  299. );
  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 register_template(&mut self, _: Template) {}
  312. fn append_children(&mut self, _: ElementId, _: usize) {}
  313. fn assign_node_id(&mut self, _: &'static [u8], _: ElementId) {}
  314. fn create_placeholder(&mut self, _: ElementId) {}
  315. fn create_text_node(&mut self, _: &str, _: ElementId) {}
  316. fn hydrate_text_node(&mut self, _: &'static [u8], _: &str, _: ElementId) {}
  317. fn load_template(&mut self, _: &'static str, _: usize, _: ElementId) {}
  318. fn replace_node_with(&mut self, _: ElementId, _: usize) {}
  319. fn replace_placeholder_with_nodes(&mut self, _: &'static [u8], _: usize) {}
  320. fn insert_nodes_after(&mut self, _: ElementId, _: usize) {}
  321. fn insert_nodes_before(&mut self, _: ElementId, _: usize) {}
  322. fn set_attribute(
  323. &mut self,
  324. _: &'static str,
  325. _: Option<&'static str>,
  326. _: &AttributeValue,
  327. _: ElementId,
  328. ) {
  329. }
  330. fn set_node_text(&mut self, _: &str, _: ElementId) {}
  331. fn create_event_listener(&mut self, name: &'static str, id: ElementId) {
  332. println!("new event listener on {:?} for {:?}", id, name);
  333. self.0.insert(id);
  334. }
  335. fn remove_event_listener(&mut self, _: &'static str, _: ElementId) {}
  336. fn remove_node(&mut self, _: ElementId) {}
  337. fn push_root(&mut self, _: ElementId) {}
  338. }