Keats / jsonwebtoken

JWT lib in rust
MIT License
1.61k stars 253 forks source link

Create Dummy Instances of Error #374

Closed ShiromMakkad closed 4 months ago

ShiromMakkad commented 4 months ago

In my unit tests, I'd like to be able to do something like:

assert_eq!(err, jsonwebtoken::errors::Error(Box::new(MissingRequiredClaim("exp".to_string()))))

But I get

error[E0603]: tuple struct constructor `Error` is private
   --> src/private/jwt/jwt.rs:164:47
    |
164 |         assert_eq!(err, jsonwebtoken::errors::Error(Box::new(MissingRequiredClaim("exp".to_string()))))
    |                                               ^^^^^ private tuple struct constructor
    |

It would be great if we could create our own errors for testing. Maybe that's a new constructor on Error, maybe that's exposing the new_error function or something else.

Another feature that would be great is for 3rd party errors, we can choose not to create an instance of the interior error. For example, with Json(Arc<serde_json::Error>). If there's a way I can assert there's been a jsonwebtoken::errors::Error::Json error, but I don't have to create a serde_json::Error because I don't care about the semantics of the serde error.

Thanks.

Keats commented 4 months ago

Why not match on the err.kind()? Right now it doesn't have any other field but it could have a source err etc that would be hard to create.

If there's a way I can assert there's been a jsonwebtoken::errors::Error::Json error, but I don't have to create a serde_json::Error because I don't care about the semantics of the serde error.

You don't know to, you can match? Eg if matches!(err, ErrorKind::Json(..))

ShiromMakkad commented 4 months ago

That works. I've got:

        match decode_jwt(invalid_idc_jwt().as_str()).await.unwrap_err() {
            JWTDecodingException::InvalidJwt(err) => {
                assert!(matches!(err.kind(), jsonwebtoken::errors::ErrorKind::Json{..}))
            }
            _ => panic!()
        }

Thanks