@@ -89,3 +89,71 @@ impl Theme {
8989 serde_yaml:: from_str :: < D > ( yaml)
9090 }
9191}
92+
93+ #[ cfg( test) ]
94+ mod tests {
95+
96+ use super :: Error ;
97+ use super :: Theme ;
98+
99+ #[ test]
100+ fn test_can_deserialize_yaml ( ) {
101+ use std:: collections:: BTreeMap ;
102+ let mut map: BTreeMap < String , String > = BTreeMap :: new ( ) ;
103+ map. insert ( "user" . to_string ( ) , "1" . to_string ( ) ) ;
104+ map. insert ( "group" . to_string ( ) , "2" . to_string ( ) ) ;
105+ assert_eq ! (
106+ map,
107+ Theme :: with_yaml(
108+ r#"---
109+ user: 1
110+ group: 2
111+ "#
112+ )
113+ . unwrap( )
114+ ) ;
115+ }
116+
117+ #[ test]
118+ fn test_ioerror ( ) {
119+ use super :: ColorTheme ;
120+
121+ let dir = assert_fs:: TempDir :: new ( ) . unwrap ( ) ;
122+ let theme = dir. path ( ) . join ( "does-not-exist.yaml" ) ;
123+
124+ let res = Theme :: from_path :: < ColorTheme > ( theme. to_str ( ) . unwrap ( ) ) ;
125+ assert ! ( res. is_err( ) ) ;
126+ let the_error = res. unwrap_err ( ) ;
127+ assert ! ( matches!( & the_error, Error :: NotExisted ( _) ) ) ;
128+ if let Error :: NotExisted ( some_err) = & the_error {
129+ assert_eq ! ( some_err. kind( ) , std:: io:: ErrorKind :: NotFound ) ;
130+ }
131+
132+ // There are many reasons why we could get an IoError, not just "file not found".
133+ // Here we test that we actually get informations about the underlying io error.
134+ assert_eq ! (
135+ "Cannot read theme file. No such file or directory (os error 2)" . to_string( ) ,
136+ the_error. to_string( )
137+ ) ;
138+ }
139+
140+ #[ test]
141+ fn test_invalid_format ( ) {
142+ use super :: ColorTheme ;
143+ use std:: fs:: File ;
144+ use std:: io:: Write ;
145+
146+ let dir = assert_fs:: TempDir :: new ( ) . unwrap ( ) ;
147+ let theme = dir. path ( ) . join ( "does-not-exist.yaml" ) ;
148+ let mut file = File :: create ( & theme) . unwrap ( ) ;
149+ // Write a purposefully bogus file
150+ writeln ! ( file, "{}" , "bogus-field: 1" ) . unwrap ( ) ;
151+
152+ let res = Theme :: from_path :: < ColorTheme > ( theme. to_str ( ) . unwrap ( ) ) ;
153+ assert ! ( res. is_err( ) ) ;
154+ // Just check the first part of serde_yaml output so that we don't break the test just adding new fields.
155+ assert ! ( res. unwrap_err( ) . to_string( ) . starts_with(
156+ "Theme file format invalid. unknown field `bogus-field`, expected one of"
157+ ) ) ;
158+ }
159+ }
0 commit comments