AppFlowy/rust-lib/flowy-ot/tests/helper/mod.rs

322 lines
11 KiB
Rust
Raw Normal View History

use derive_more::Display;
2021-08-03 23:55:54 +00:00
use flowy_ot::core::*;
2021-07-31 12:53:45 +00:00
use rand::{prelude::*, Rng as WrappedRng};
use std::sync::Once;
2021-07-31 12:53:45 +00:00
#[derive(Clone, Debug, Display)]
2021-08-04 07:09:04 +00:00
pub enum TestOp {
#[display(fmt = "Insert")]
2021-08-03 15:13:20 +00:00
Insert(usize, &'static str, usize),
// delta_i, s, start, length,
#[display(fmt = "InsertBold")]
InsertBold(usize, &'static str, Interval),
// delta_i, start, length, enable
#[display(fmt = "Bold")]
Bold(usize, Interval, bool),
#[display(fmt = "Delete")]
2021-08-03 08:20:25 +00:00
Delete(usize, Interval),
#[display(fmt = "Italic")]
2021-08-02 15:08:24 +00:00
Italic(usize, Interval, bool),
#[display(fmt = "Transform")]
Transform(usize, usize),
// invert the delta_a base on the delta_b
#[display(fmt = "Invert")]
Invert(usize, usize),
#[display(fmt = "AssertStr")]
AssertStr(usize, &'static str),
#[display(fmt = "AssertOpsJson")]
AssertOpsJson(usize, &'static str),
}
2021-08-04 07:09:04 +00:00
pub struct OpTester {
deltas: Vec<Delta>,
}
2021-08-04 07:09:04 +00:00
impl OpTester {
pub fn new() -> Self {
static INIT: Once = Once::new();
INIT.call_once(|| {
2021-08-02 15:08:24 +00:00
std::env::set_var("RUST_LOG", "info");
env_logger::init();
});
let mut deltas = Vec::with_capacity(2);
for _ in 0..2 {
let delta = Delta::default();
deltas.push(delta);
}
Self { deltas }
}
2021-08-04 07:09:04 +00:00
pub fn run_op(&mut self, op: &TestOp) {
log::debug!("***************** 😈{} *******************", &op);
match op {
2021-08-04 07:09:04 +00:00
TestOp::Insert(delta_i, s, index) => {
2021-08-03 15:13:20 +00:00
self.update_delta_with_insert(*delta_i, s, *index);
},
2021-08-04 07:09:04 +00:00
TestOp::Delete(delta_i, interval) => {
2021-08-03 08:20:25 +00:00
//
self.update_delta_with_delete(*delta_i, interval);
},
2021-08-04 07:09:04 +00:00
TestOp::InsertBold(delta_i, s, _interval) => {
2021-08-02 15:08:24 +00:00
let attrs = AttrsBuilder::new().bold(true).build();
let delta = &mut self.deltas[*delta_i];
2021-08-03 08:20:25 +00:00
delta.insert(s, attrs);
},
2021-08-04 07:09:04 +00:00
TestOp::Bold(delta_i, interval, enable) => {
2021-08-02 15:08:24 +00:00
let attrs = AttrsBuilder::new().bold(*enable).build();
2021-08-03 08:20:25 +00:00
self.update_delta_with_attribute(*delta_i, attrs, interval);
2021-08-02 15:08:24 +00:00
},
2021-08-04 07:09:04 +00:00
TestOp::Italic(delta_i, interval, enable) => {
2021-08-02 15:08:24 +00:00
let attrs = AttrsBuilder::new().italic(*enable).build();
2021-08-03 08:20:25 +00:00
self.update_delta_with_attribute(*delta_i, attrs, interval);
},
2021-08-04 07:09:04 +00:00
TestOp::Transform(delta_a_i, delta_b_i) => {
let delta_a = &self.deltas[*delta_a_i];
let delta_b = &self.deltas[*delta_b_i];
let (a_prime, b_prime) = delta_a.transform(delta_b).unwrap();
2021-08-03 08:20:25 +00:00
log::trace!("a:{:?},b:{:?}", a_prime, b_prime);
let new_delta_a = delta_a.compose(&b_prime).unwrap();
let new_delta_b = delta_b.compose(&a_prime).unwrap();
self.deltas[*delta_a_i] = new_delta_a;
self.deltas[*delta_b_i] = new_delta_b;
},
TestOp::Invert(delta_a_i, delta_b_i) => {
let delta_a = &self.deltas[*delta_a_i];
let delta_b = &self.deltas[*delta_b_i];
log::debug!("Invert: ");
log::debug!("a: {}", delta_a.to_json());
log::debug!("b: {}", delta_b.to_json());
let (_, b_prime) = delta_a.transform(delta_b).unwrap();
let undo = b_prime.invert_delta(&delta_a);
let new_delta = delta_a.compose(&b_prime).unwrap();
log::debug!("new delta: {}", new_delta.to_json());
log::debug!("undo delta: {}", undo.to_json());
let new_delta_after_undo = new_delta.compose(&undo).unwrap();
log::debug!("inverted delta a: {}", new_delta_after_undo.to_string());
assert_eq!(delta_a, &new_delta_after_undo);
self.deltas[*delta_a_i] = new_delta_after_undo;
},
2021-08-04 07:09:04 +00:00
TestOp::AssertStr(delta_i, expected) => {
let s = self.deltas[*delta_i].apply("").unwrap();
assert_eq!(&s, expected);
},
2021-08-04 07:09:04 +00:00
TestOp::AssertOpsJson(delta_i, expected) => {
2021-08-04 14:33:16 +00:00
log::debug!("AssertOpsJson: {:?}", self.deltas[*delta_i]);
2021-08-02 15:08:24 +00:00
let delta_i_json = serde_json::to_string(&self.deltas[*delta_i]).unwrap();
2021-08-03 08:20:25 +00:00
let expected_delta: Delta = serde_json::from_str(expected).unwrap();
let target_delta: Delta = serde_json::from_str(&delta_i_json).unwrap();
if expected_delta != target_delta {
2021-08-03 15:13:20 +00:00
log::error!("✅ expect: {}", expected,);
log::error!("❌ receive: {}", delta_i_json);
2021-08-02 15:08:24 +00:00
}
2021-08-03 08:20:25 +00:00
assert_eq!(target_delta, expected_delta);
},
}
}
2021-08-04 07:09:04 +00:00
pub fn run_script(&mut self, script: Vec<TestOp>) {
2021-08-03 08:20:25 +00:00
for (_i, op) in script.iter().enumerate() {
self.run_op(op);
}
}
2021-08-02 15:08:24 +00:00
2021-08-04 07:09:04 +00:00
pub fn get_delta(&mut self, index: usize) -> &mut Delta { &mut self.deltas[index] }
2021-08-03 15:13:20 +00:00
pub fn update_delta_with_insert(&mut self, delta_index: usize, s: &str, index: usize) {
let old_delta = &mut self.deltas[delta_index];
let target_interval = Interval::new(0, old_delta.target_len);
if old_delta.target_len < index {
log::error!("{} out of bounds {}", index, target_interval);
}
2021-08-04 07:09:04 +00:00
let mut attributes = old_delta.attributes_in_interval(Interval::new(index, index + 1));
2021-08-03 15:13:20 +00:00
if attributes == Attributes::Empty {
attributes = Attributes::Follow;
}
let insert = OpBuilder::insert(s).attributes(attributes).build();
2021-08-03 23:55:54 +00:00
let new_delta = new_delta_with_op(old_delta, insert, Interval::new(index, index));
2021-08-03 15:13:20 +00:00
self.deltas[delta_index] = new_delta;
}
2021-08-03 08:20:25 +00:00
pub fn update_delta_with_attribute(
2021-08-02 15:08:24 +00:00
&mut self,
delta_index: usize,
2021-08-05 03:30:29 +00:00
mut attributes: Attributes,
2021-08-02 15:08:24 +00:00
interval: &Interval,
) {
let old_delta = &self.deltas[delta_index];
2021-08-05 03:30:29 +00:00
let old_attributes = old_delta.attributes_in_interval(*interval);
log::debug!(
"merge attributes: {:?}, with old: {:?}",
attributes,
old_attributes
);
2021-08-05 03:30:29 +00:00
let new_attributes = match &mut attributes {
Attributes::Follow => old_attributes,
Attributes::Custom(attr_data) => {
attr_data.merge(old_attributes.data());
attr_data.clone().into_attributes()
},
Attributes::Empty => Attributes::Empty,
};
log::debug!("new attributes: {:?}", new_attributes);
2021-08-05 03:30:29 +00:00
let retain = OpBuilder::retain(interval.size() as u64)
.attributes(new_attributes)
2021-08-03 08:20:25 +00:00
.build();
2021-08-03 15:13:20 +00:00
2021-08-04 14:33:16 +00:00
log::debug!(
"Update delta with new attributes: {:?} at: {:?}",
2021-08-04 14:33:16 +00:00
retain,
interval
);
2021-08-03 15:13:20 +00:00
2021-08-03 23:55:54 +00:00
let new_delta = new_delta_with_op(old_delta, retain, *interval);
2021-08-02 15:08:24 +00:00
self.deltas[delta_index] = new_delta;
}
2021-08-03 08:20:25 +00:00
pub fn update_delta_with_delete(&mut self, delta_index: usize, interval: &Interval) {
let old_delta = &self.deltas[delta_index];
2021-08-04 14:33:16 +00:00
let delete = OpBuilder::delete(interval.size() as u64).build();
2021-08-03 23:55:54 +00:00
let new_delta = new_delta_with_op(old_delta, delete, *interval);
2021-08-03 08:20:25 +00:00
self.deltas[delta_index] = new_delta;
}
}
2021-08-02 15:08:24 +00:00
2021-08-03 23:55:54 +00:00
fn new_delta_with_op(delta: &Delta, op: Operation, interval: Interval) -> Delta {
2021-08-02 15:08:24 +00:00
let mut new_delta = Delta::default();
2021-08-03 23:55:54 +00:00
let (prefix, interval, suffix) = target_length_split_with_interval(delta.target_len, interval);
2021-08-03 08:20:25 +00:00
// prefix
2021-08-03 15:13:20 +00:00
if prefix.is_empty() == false && prefix != interval {
let intervals = split_interval_with_delta(delta, &prefix);
2021-08-04 14:33:16 +00:00
intervals.into_iter().for_each(|p_interval| {
let attributes = delta.attributes_in_interval(p_interval);
log::debug!(
"prefix attribute: {:?}, interval: {:?}",
attributes,
p_interval
);
new_delta.retain(p_interval.size() as u64, attributes);
2021-08-03 15:13:20 +00:00
});
2021-08-02 15:08:24 +00:00
}
log::debug!("add new op: {:?}", op);
2021-08-03 08:20:25 +00:00
new_delta.add(op);
2021-08-02 15:08:24 +00:00
2021-08-03 08:20:25 +00:00
// suffix
2021-08-02 15:08:24 +00:00
if suffix.is_empty() == false {
2021-08-03 15:13:20 +00:00
let intervals = split_interval_with_delta(delta, &suffix);
2021-08-04 14:33:16 +00:00
intervals.into_iter().for_each(|s_interval| {
let attributes = delta.attributes_in_interval(s_interval);
log::debug!(
"suffix attribute: {:?}, interval: {:?}",
attributes,
s_interval
);
new_delta.retain(s_interval.size() as u64, attributes);
2021-08-03 15:13:20 +00:00
});
2021-08-02 15:08:24 +00:00
}
delta.compose(&new_delta).unwrap()
}
2021-08-03 15:13:20 +00:00
fn split_interval_with_delta(delta: &Delta, interval: &Interval) -> Vec<Interval> {
let mut start = 0;
let mut new_intervals = vec![];
delta.ops.iter().for_each(|op| match op {
Operation::Delete(_) => {},
Operation::Retain(_) => {},
Operation::Insert(insert) => {
let len = insert.num_chars() as usize;
let end = start + len;
let insert_interval = Interval::new(start, end);
let new_interval = interval.intersect(insert_interval);
if !new_interval.is_empty() {
new_intervals.push(new_interval)
}
start += len;
},
});
new_intervals
}
pub fn target_length_split_with_interval(
length: usize,
interval: Interval,
) -> (Interval, Interval, Interval) {
2021-08-03 08:20:25 +00:00
let original_interval = Interval::new(0, length);
2021-08-03 15:13:20 +00:00
let prefix = original_interval.prefix(interval);
let suffix = original_interval.suffix(interval);
(prefix, interval, suffix)
2021-08-03 08:20:25 +00:00
}
pub fn debug_print_delta(delta: &Delta) {
2021-08-04 07:09:04 +00:00
eprintln!("😁 {}", serde_json::to_string(delta).unwrap());
2021-08-03 08:20:25 +00:00
}
pub struct Rng(StdRng);
impl Default for Rng {
fn default() -> Self { Rng(StdRng::from_rng(thread_rng()).unwrap()) }
}
impl Rng {
pub fn from_seed(seed: [u8; 32]) -> Self { Rng(StdRng::from_seed(seed)) }
pub fn gen_string(&mut self, len: usize) -> String {
(0..len).map(|_| self.0.gen::<char>()).collect()
}
pub fn gen_delta(&mut self, s: &str) -> Delta {
let mut delta = Delta::default();
loop {
2021-08-04 07:09:04 +00:00
let left = s.chars().count() - delta.base_len;
2021-08-03 08:20:25 +00:00
if left == 0 {
break;
}
let i = if left == 1 {
1
} else {
1 + self.0.gen_range(0, std::cmp::min(left - 1, 20))
};
match self.0.gen_range(0.0, 1.0) {
f if f < 0.2 => {
delta.insert(&self.gen_string(i), Attributes::Empty);
},
f if f < 0.4 => {
delta.delete(i as u64);
},
_ => {
delta.retain(i as u64, Attributes::Empty);
},
}
}
if self.0.gen_range(0.0, 1.0) < 0.3 {
delta.insert(&("1".to_owned() + &self.gen_string(10)), Attributes::Empty);
}
delta
}
}