fuzzing.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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: concat!(file!(), ":", line!(), ":", column!(), ":0"),
  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. #[derive(PartialEq, Props, Clone)]
  218. struct DepthProps {
  219. depth: usize,
  220. root: bool,
  221. }
  222. fn create_random_element(cx: DepthProps) -> Element {
  223. if rand::random::<usize>() % 10 == 0 {
  224. needs_update();
  225. }
  226. let range = if cx.root { 2 } else { 3 };
  227. let node = match rand::random::<usize>() % range {
  228. 0 | 1 => {
  229. let (template, dynamic_node_types) = create_random_template(Box::leak(
  230. format!(
  231. "{}{}",
  232. concat!(file!(), ":", line!(), ":", column!(), ":"),
  233. {
  234. unsafe {
  235. let old = TEMPLATE_COUNT;
  236. TEMPLATE_COUNT += 1;
  237. old
  238. }
  239. }
  240. )
  241. .into_boxed_str(),
  242. ));
  243. let node = VNode::new(
  244. None,
  245. template,
  246. dynamic_node_types
  247. .iter()
  248. .map(|ty| match ty {
  249. DynamicNodeType::Text => {
  250. DynamicNode::Text(VText::new(format!("{}", rand::random::<usize>())))
  251. }
  252. DynamicNodeType::Other => create_random_dynamic_node(cx.depth + 1),
  253. })
  254. .collect(),
  255. (0..template.attr_paths.len())
  256. .map(|_| Box::new([create_random_dynamic_attr()]) as Box<[Attribute]>)
  257. .collect(),
  258. );
  259. Some(node)
  260. }
  261. _ => None,
  262. };
  263. // println!("{node:#?}");
  264. node
  265. }
  266. // test for panics when creating random nodes and templates
  267. #[test]
  268. fn create() {
  269. let repeat_count = if cfg!(miri) { 100 } else { 1000 };
  270. for _ in 0..repeat_count {
  271. let mut vdom =
  272. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  273. vdom.rebuild(&mut NoOpMutations);
  274. }
  275. }
  276. // test for panics when diffing random nodes
  277. // This test will change the template every render which is not very realistic, but it helps stress the system
  278. #[test]
  279. fn diff() {
  280. let repeat_count = if cfg!(miri) { 100 } else { 1000 };
  281. for _ in 0..repeat_count {
  282. let mut vdom =
  283. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  284. vdom.rebuild(&mut NoOpMutations);
  285. // A list of all elements that have had event listeners
  286. // This is intentionally never cleared, so that we can test that calling event listeners that are removed doesn't cause a panic
  287. let mut event_listeners = HashSet::new();
  288. for _ in 0..100 {
  289. for &id in &event_listeners {
  290. println!("firing event on {:?}", id);
  291. vdom.handle_event(
  292. "data",
  293. std::rc::Rc::new(String::from("hello world")),
  294. id,
  295. true,
  296. );
  297. }
  298. {
  299. let muts = vdom.render_immediate_to_vec();
  300. for mut_ in muts.edits {
  301. if let Mutation::NewEventListener { name, id } = mut_ {
  302. println!("new event listener on {:?} for {:?}", id, name);
  303. event_listeners.insert(id);
  304. }
  305. }
  306. }
  307. }
  308. }
  309. }