From 144ecc5ef9064b3e8e820329f00a84a50e6762eb Mon Sep 17 00:00:00 2001 From: "D.Loh" Date: Fri, 7 Feb 2020 09:08:40 -0800 Subject: add unit test, and do not truncate when len equal --- askama_shared/src/filters/mod.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'askama_shared/src') diff --git a/askama_shared/src/filters/mod.rs b/askama_shared/src/filters/mod.rs index 11216a5..eeb9e52 100644 --- a/askama_shared/src/filters/mod.rs +++ b/askama_shared/src/filters/mod.rs @@ -158,7 +158,7 @@ pub fn trim(s: &dyn fmt::Display) -> Result { /// Limit string length, appends '...' if truncated pub fn truncate(s: &dyn fmt::Display, len: &usize) -> Result { let mut s = s.to_string(); - if s.len() < *len { + if s.len() <= *len { Ok(s) } else { let mut real_len = *len; @@ -348,6 +348,28 @@ mod tests { fn test_trim() { assert_eq!(trim(&" Hello\tworld\t").unwrap(), "Hello\tworld"); } + + #[test] + fn test_truncate() { + assert_eq!(truncate(&"hello", &2).unwrap(), "he..."); + let a = String::from("您好"); + assert_eq!(a.len(), 6); + assert_eq!(String::from("您").len(), 3); + assert_eq!(truncate(&"您好", &1).unwrap(), "您..."); + assert_eq!(truncate(&"您好", &2).unwrap(), "您..."); + assert_eq!(truncate(&"您好", &3).unwrap(), "您..."); + assert_eq!(truncate(&"您好", &6).unwrap(), "您好"); + assert_eq!(truncate(&"您好", &7).unwrap(), "您好"); + let s = String::from("🤚a🤚"); + assert_eq!(s.len(), 9); + assert_eq!(String::from("🤚").len(), 4); + assert_eq!(truncate(&"🤚a🤚", &1).unwrap(), "🤚..."); + assert_eq!(truncate(&"🤚a🤚", &2).unwrap(), "🤚..."); + assert_eq!(truncate(&"🤚a🤚", &3).unwrap(), "🤚..."); + assert_eq!(truncate(&"🤚a🤚", &4).unwrap(), "🤚..."); + assert_eq!(truncate(&"🤚a🤚", &9).unwrap(), "🤚a🤚"); + assert_eq!(truncate(&"🤚a🤚", &10).unwrap(), "🤚a🤚"); + } #[test] fn test_indent() { -- cgit