Skip to content

Commit

Permalink
fj: add unit tests for Sketch
Browse files Browse the repository at this point in the history
  • Loading branch information
kamirr committed Jun 11, 2022
1 parent 46603a5 commit 50238b3
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/fj/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
58 changes: 58 additions & 0 deletions crates/fj/src/shape_2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,3 +311,61 @@ impl From<Sketch> 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());
}
}

0 comments on commit 50238b3

Please sign in to comment.