@@ -196,27 +196,39 @@ impl TestResponse {
196196 self . 0 . headers . iter ( )
197197 }
198198
199+ pub fn content ( & self , content_type : & ' static str ) -> Option < & [ u8 ] > {
200+ let _= self . 0 . headers . ContentType ( ) ?. starts_with ( content_type)
201+ . then_some ( ( ) ) ?;
202+ let bytes = self . 0 . content . as_bytes ( ) ?;
203+ assert_eq ! (
204+ bytes. len( ) ,
205+ self . 0 . headers. ContentLength ( ) ?. parse:: <usize >( ) . unwrap( ) ,
206+ "Content-Length does not match the actual content length"
207+ ) ;
208+ Some ( bytes)
209+ }
199210 pub fn text ( & self ) -> Option < & str > {
200- if self . 0 . headers . ContentType ( ) ?. starts_with ( "text/plain" ) {
201- let body = self . 0 . content . as_bytes ( ) ?;
202- Some ( std:: str:: from_utf8 ( body) . expect ( & f ! ( "Response content is not UTF-8: {}" , body. escape_ascii( ) ) ) )
203- } else { None }
211+ self . content ( "text/plain" )
212+ . map ( |bytes| std:: str:: from_utf8 ( bytes) . expect ( & f ! (
213+ "Response content is not UTF-8: {}" ,
214+ bytes. escape_ascii( )
215+ ) ) )
204216 }
205217 pub fn html ( & self ) -> Option < & str > {
206- if self . 0 . headers . ContentType ( ) ? . starts_with ( "text/html" ) {
207- let body = self . 0 . content . as_bytes ( ) ? ;
208- Some ( std :: str :: from_utf8 ( body ) . expect ( & f ! ( "Response content is not UTF-8: {}" , body . escape_ascii ( ) ) ) )
209- } else { None }
210- }
211- pub fn json < ' d , JSON : serde :: Deserialize < ' d > > ( & ' d self ) -> Option < serde_json :: Result < JSON > > {
212- if self . 0 . headers . ContentType ( ) ? . starts_with ( "application/json" ) {
213- let body = self . 0 . content . as_bytes ( ) ? ;
214- Some ( serde_json:: from_slice ( body ) )
215- } else { None }
216- }
217- pub fn content ( & self , content_type : & ' static str ) -> Option < & [ u8 ] > {
218- if self . 0 . headers . ContentType ( ) ? . starts_with ( content_type ) {
219- self . 0 . content . as_bytes ( )
220- } else { None }
218+ self . content ( "text/html" )
219+ . map ( |bytes| std :: str :: from_utf8 ( bytes ) . expect ( & f ! (
220+ "Response content is not UTF-8: {}" ,
221+ bytes . escape_ascii ( )
222+ ) ) )
223+ }
224+ pub fn json < ' d , T : serde :: Deserialize < ' d > > ( & ' d self ) -> Option < Result < T , serde_json :: Error > > {
225+ self . content ( "application/json" )
226+ . map ( |bytes| serde_json:: from_slice ( bytes )
227+ // .expect(&f!(
228+ // "Failed to deserialize json payload as {}: {}",
229+ // std::any::type_name::<T>(),
230+ // bytes.escape_ascii()
231+ // ) )
232+ )
221233 }
222234}
0 commit comments