From 50238b3fae19130b4732f47d86359cf798ad4162 Mon Sep 17 00:00:00 2001 From: Kamil Koczurek Date: Sat, 11 Jun 2022 16:43:02 +0200 Subject: [PATCH] fj: add unit tests for Sketch --- Cargo.lock | 1 + crates/fj/Cargo.toml | 3 ++ crates/fj/src/shape_2d.rs | 58 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index e367d796c..0e84b4567 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -692,6 +692,7 @@ version = "0.6.0" dependencies = [ "fj-proc", "serde", + "serde_json", ] [[package]] diff --git a/crates/fj/Cargo.toml b/crates/fj/Cargo.toml index 40e7e8f08..83cd0801b 100644 --- a/crates/fj/Cargo.toml +++ b/crates/fj/Cargo.toml @@ -18,5 +18,8 @@ serialization = ["serde"] [dependencies] serde = { version = "1.0.7", features = ["derive"], optional = true } +[dev-dependencies] +serde_json = "1.0.81" + [dependencies.fj-proc] path = "../../crates/fj-proc" \ No newline at end of file diff --git a/crates/fj/src/shape_2d.rs b/crates/fj/src/shape_2d.rs index fe7ff371c..269b5dba2 100644 --- a/crates/fj/src/shape_2d.rs +++ b/crates/fj/src/shape_2d.rs @@ -311,3 +311,61 @@ impl From for Shape2d { // `Sketch` can be `Send`, because it encapsulates the raw pointer it contains, // making sure memory ownership rules are observed. unsafe impl Send for Sketch {} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_points() -> Vec<[f64; 2]> { + vec![[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]] + } + + #[test] + fn test_sketch_preserve_points() { + let points = test_points(); + let sketch = Sketch::from_points(points.clone()); + + assert_eq!(sketch.to_points(), points); + } + + #[test] + fn test_sketch_rc() { + let assert_rc = |sketch: &Sketch, expected_rc: usize| { + let rc = unsafe { (*sketch.rc).load(atomic::Ordering::Acquire) }; + assert_eq!( + rc, expected_rc, + "Sketch has rc = {rc}, expected {expected_rc}" + ); + }; + + let sketch = Sketch::from_points(test_points()); + assert_rc(&sketch, 1); + + let (s2, s3) = (sketch.clone(), sketch.clone()); + assert_rc(&sketch, 3); + + drop(s2); + assert_rc(&sketch, 2); + + drop(s3); + assert_rc(&sketch, 1); + + // rc is deallocated after the last drop, so we can't assert that it's 0 + } + + #[cfg(feature = "serialization")] + #[test] + fn test_serialize_loopback() { + use serde_json::{from_str, to_string}; + + let sketch = Sketch::from_points(test_points()); + + let json = to_string(&sketch).expect("failed to serialize sketch"); + let sketch_de: Sketch = + from_str(&json).expect("failed to deserialize sketch"); + + // ensure same content + assert_eq!(sketch.to_points(), sketch_de.to_points()); + assert_eq!(sketch.color(), sketch_de.color()); + } +}