simplejrpc 0.1.0

Unix-socket JSON-RPC 2.0 SDK with middleware, config, and validation
Documentation
//! Public API tests for `Error` / `ErrorMapping` extensibility.

use simplejrpc::error::{Error, ErrorMapping};
use simplejrpc::{sanitize::CLIENT_INTERNAL_MSG, RpcCode};

#[test]
fn builtin_mapping() {
    let e = Error::biz(RpcCode::Forbidden, "denied");
    assert_eq!(e.code(), 200_403);
    assert!(e.is_public());
    assert_eq!(e.client_message(), "denied");

    assert_eq!(
        Error::Protocol("x".into()).client_message(),
        CLIENT_INTERNAL_MSG
    );
}

#[test]
fn override_client_message_via_wrapper() {
    struct Prefixed(Error);

    impl ErrorMapping for Prefixed {
        fn code(&self) -> i32 {
            ErrorMapping::code(&self.0)
        }
        fn is_public(&self) -> bool {
            ErrorMapping::is_public(&self.0)
        }
        fn client_message(&self) -> String {
            format!("app: {}", ErrorMapping::client_message(&self.0))
        }
    }

    let p = Prefixed(Error::biz(RpcCode::BadRequest, "bad"));
    assert_eq!(ErrorMapping::client_message(&p), "app: bad");
    let resp = p.to_app_response("add");
    assert_eq!(resp.code, 200_400);
    assert_eq!(resp.message, "app: bad");
    assert_eq!(resp.meta.endpoint, "add");
}

#[test]
fn override_to_app_response_adds_meta_close() {
    struct CloseOnError(Error);

    impl ErrorMapping for CloseOnError {
        fn code(&self) -> i32 {
            ErrorMapping::code(&self.0)
        }
        fn is_public(&self) -> bool {
            ErrorMapping::is_public(&self.0)
        }
        fn client_message(&self) -> String {
            ErrorMapping::client_message(&self.0)
        }
        fn to_app_response(&self, endpoint: impl Into<String>) -> simplejrpc::AppResponse {
            ErrorMapping::to_app_response(&self.0, endpoint).with_close(1)
        }
    }

    let resp = CloseOnError(Error::biz(RpcCode::Forbidden, "no"))
        .to_app_response("x");
    assert_eq!(resp.code, 200_403);
    assert_eq!(resp.meta.close, 1);
}