fuzzing.rs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. use dioxus::prelude::Props;
  2. use dioxus_core::*;
  3. use std::cell::Cell;
  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 > 3 { 1 } else { 3 };
  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. _ => unreachable!(),
  187. }
  188. }
  189. fn create_random_dynamic_attr(cx: &ScopeState) -> Attribute {
  190. let value = match rand::random::<u8>() % 6 {
  191. 0 => AttributeValue::Text(Box::leak(
  192. format!("{}", rand::random::<usize>()).into_boxed_str(),
  193. )),
  194. 1 => AttributeValue::Float(rand::random()),
  195. 2 => AttributeValue::Int(rand::random()),
  196. 3 => AttributeValue::Bool(rand::random()),
  197. 4 => cx.any_value(rand::random::<usize>()),
  198. 5 => AttributeValue::None,
  199. // Listener(RefCell<Option<ListenerCb<'a>>>),
  200. _ => unreachable!(),
  201. };
  202. Attribute {
  203. name: Box::leak(format!("attr{}", rand::random::<usize>()).into_boxed_str()),
  204. value,
  205. namespace: random_ns(),
  206. mounted_element: Default::default(),
  207. volatile: rand::random(),
  208. }
  209. }
  210. static mut TEMPLATE_COUNT: usize = 0;
  211. #[derive(PartialEq, Props)]
  212. struct DepthProps {
  213. depth: usize,
  214. root: bool,
  215. }
  216. fn create_random_element(cx: Scope<DepthProps>) -> Element {
  217. cx.needs_update();
  218. let range = if cx.props.root { 2 } else { 3 };
  219. let node = match rand::random::<usize>() % range {
  220. 0 | 1 => {
  221. let (template, dynamic_node_types) = create_random_template(Box::leak(
  222. format!(
  223. "{}{}",
  224. concat!(file!(), ":", line!(), ":", column!(), ":"),
  225. {
  226. unsafe {
  227. let old = TEMPLATE_COUNT;
  228. TEMPLATE_COUNT += 1;
  229. old
  230. }
  231. }
  232. )
  233. .into_boxed_str(),
  234. ));
  235. println!("{template:#?}");
  236. let node = VNode {
  237. key: None,
  238. parent: None,
  239. template: Cell::new(template),
  240. root_ids: Default::default(),
  241. dynamic_nodes: {
  242. let dynamic_nodes: Vec<_> = dynamic_node_types
  243. .iter()
  244. .map(|ty| match ty {
  245. DynamicNodeType::Text => DynamicNode::Text(VText {
  246. value: Box::leak(
  247. format!("{}", rand::random::<usize>()).into_boxed_str(),
  248. ),
  249. id: Default::default(),
  250. }),
  251. DynamicNodeType::Other => {
  252. create_random_dynamic_node(cx, cx.props.depth + 1)
  253. }
  254. })
  255. .collect();
  256. cx.bump().alloc(dynamic_nodes)
  257. },
  258. dynamic_attrs: cx.bump().alloc(
  259. (0..template.attr_paths.len())
  260. .map(|_| create_random_dynamic_attr(cx))
  261. .collect::<Vec<_>>(),
  262. ),
  263. };
  264. Some(node)
  265. }
  266. _ => None,
  267. };
  268. println!("{node:#?}");
  269. node
  270. }
  271. // test for panics when creating random nodes and templates
  272. #[test]
  273. fn create() {
  274. for _ in 0..100 {
  275. let mut vdom =
  276. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  277. let _ = vdom.rebuild();
  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. for _ in 0..10 {
  285. let mut vdom =
  286. VirtualDom::new_with_props(create_random_element, DepthProps { depth: 0, root: true });
  287. let _ = vdom.rebuild();
  288. for _ in 0..10 {
  289. let _ = vdom.render_immediate();
  290. }
  291. }
  292. }