diff options
author | René Kijewski <Kijewski@users.noreply.github.com> | 2022-01-28 10:48:46 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-28 10:48:46 +0100 |
commit | 85ad2e6ba3a205e9b648431318aac0e75c027a82 (patch) | |
tree | 5e186e2b9d4efcc97666a9d58410dfda238f5735 /testing | |
parent | cb351fe6b1dda644a4ec023dc850cdfe83732503 (diff) | |
download | askama-85ad2e6ba3a205e9b648431318aac0e75c027a82.tar.gz askama-85ad2e6ba3a205e9b648431318aac0e75c027a82.tar.bz2 askama-85ad2e6ba3a205e9b648431318aac0e75c027a82.zip |
Implement error propagation expression: `?` (#590)
This change allows using the operator `?` in askama expressions. It
works like the same operator in Rust: if a `Result` is `Ok`, it is
unwrapped. If it is an error, then the `render()` method fails with this
error value.
Diffstat (limited to 'testing')
-rw-r--r-- | testing/tests/try.rs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/testing/tests/try.rs b/testing/tests/try.rs new file mode 100644 index 0000000..e199f9c --- /dev/null +++ b/testing/tests/try.rs @@ -0,0 +1,69 @@ +use askama::Template; + +#[derive(Template)] +#[template(source = "{% let v = self.parse()? %}{{s}}={{v}}", ext = "txt")] +struct IntParserTemplate<'a> { + s: &'a str, +} + +impl IntParserTemplate<'_> { + fn parse(&self) -> Result<i32, std::num::ParseIntError> { + self.s.parse() + } +} + +#[test] +fn test_int_parser() { + let template = IntParserTemplate { s: "💯" }; + assert!(matches!(template.render(), Err(askama::Error::Custom(_)))); + assert_eq!( + format!("{}", &template.render().unwrap_err()), + "invalid digit found in string" + ); + + let template = IntParserTemplate { s: "100" }; + assert_eq!(template.render().unwrap(), "100=100"); +} + +#[derive(Template)] +#[template(source = "{{ value()? }}", ext = "txt")] +struct FailFmt { + value: fn() -> Result<&'static str, std::fmt::Error>, +} + +#[test] +fn fail_fmt() { + let template = FailFmt { + value: || Err(std::fmt::Error), + }; + assert!(matches!(template.render(), Err(askama::Error::Custom(_)))); + assert_eq!( + format!("{}", &template.render().unwrap_err()), + format!("{}", std::fmt::Error) + ); + + let template = FailFmt { + value: || Ok("hello world"), + }; + assert_eq!(template.render().unwrap(), "hello world"); +} + +#[derive(Template)] +#[template(source = "{{ value()? }}", ext = "txt")] +struct FailStr { + value: fn() -> Result<&'static str, &'static str>, +} + +#[test] +fn fail_str() { + let template = FailStr { + value: || Err("FAIL"), + }; + assert!(matches!(template.render(), Err(askama::Error::Custom(_)))); + assert_eq!(format!("{}", &template.render().unwrap_err()), "FAIL"); + + let template = FailStr { + value: || Ok("hello world"), + }; + assert_eq!(template.render().unwrap(), "hello world"); +} |