Skip to content

Commit

Permalink
test error display and debug impl
Browse files Browse the repository at this point in the history
Signed-off-by: simonsan <[email protected]>
  • Loading branch information
simonsan committed Oct 25, 2024
1 parent ae1c33d commit a28089d
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 51 deletions.
4 changes: 1 addition & 3 deletions crates/core/src/backend/decrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -541,9 +541,7 @@ impl<C: CryptoKey> DecryptReadBackend for DecryptBackend<C> {
///
/// A vector containing the decrypted data.
fn decrypt(&self, data: &[u8]) -> RusticResult<Vec<u8>> {
self.key
.decrypt_data(data)
.map_err(|_err| todo!("Error transition"))
self.key.decrypt_data(data)
}

/// Reads encrypted data from the backend.
Expand Down
50 changes: 5 additions & 45 deletions crates/core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,20 @@ pub struct RusticError {

impl Display for RusticError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "An error occurred in `rustic_core`: {}", self.kind)?;
write!(f, "{} occurred in `rustic_core`", self.kind)?;

write!(f, "\nMessage: {}", self.guidance)?;
write!(f, "\n\nMessage:\n{}", self.guidance)?;

if !self.context.is_empty() {
write!(f, "\n\n Context:\n")?;
write!(f, "\n\nContext:\n")?;
write!(
f,
"{}",
self.context
.iter()
.map(|(k, v)| format!("{k}: {v}"))
.collect::<Vec<_>>()
.join(", ")
.join(",\n")
)?;
}

Expand All @@ -94,7 +94,7 @@ impl Display for RusticError {
let default_docs_url = SmolStr::from(constants::DEFAULT_DOCS_URL);
let docs_url = self.docs_url.as_ref().unwrap_or(&default_docs_url);

write!(f, "\n\nFor more information, see: {docs_url}/{code}")?;
write!(f, "\n\nFor more information, see: {docs_url}{code}")?;
}

if let Some(existing_issue_url) = &self.existing_issue_url {
Expand Down Expand Up @@ -335,43 +335,3 @@ pub enum ErrorKind {
// - **Backend Access Errors**: e.g., `BackendNotSupported`, `BackendLoadError`, `NoSuitableIdFound`, `IdNotUnique`
// - **Rclone Errors**: e.g., `NoOutputForRcloneVersion`, `NoStdOutForRclone`, `RCloneExitWithBadStatus`
// - **REST API Errors**: e.g., `NotSupportedForRetry`, `UrlParsingFailed`

#[cfg(test)]
mod tests {
use std::sync::LazyLock;

use super::*;

static TEST_ERROR: LazyLock<RusticError> = LazyLock::new(|| RusticError {
kind: ErrorKind::Io,
guidance:
"A file could not be read, make sure the file is existing and readable by the system."
.into(),
status: Some(Status::Permanent),
severity: Some(Severity::Error),
code: Some("E001".to_string().into()),
context: vec![
("path", "/path/to/file".into()),
("called", "used s3 backend".into()),
]
.into_boxed_slice(),
source: Some(Box::new(std::io::Error::new(
std::io::ErrorKind::Other,
"networking error",
))),
backtrace: Some(Backtrace::disabled()),
docs_url: None,
new_issue_url: None,
existing_issue_url: None,
});

#[test]
fn test_error_display() {
insta::assert_snapshot!(TEST_ERROR.to_string());
}

#[test]
fn test_error_debug() {
insta::assert_debug_snapshot!(TEST_ERROR);
}
}
2 changes: 1 addition & 1 deletion crates/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ pub use crate::{
repoinfo::{BlobInfo, IndexInfos, PackInfo, RepoFileInfo, RepoFileInfos},
restore::{FileDirStats, RestoreOptions, RestorePlan, RestoreStats},
},
error::{ErrorKind, RusticError, RusticResult, Severity},
error::{ErrorKind, RusticError, RusticResult, Severity, Status},
id::{HexId, Id},
progress::{NoProgress, NoProgressBars, Progress, ProgressBars},
repofile::snapshotfile::{
Expand Down
4 changes: 2 additions & 2 deletions crates/core/src/repofile/keyfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,14 +259,14 @@ impl KeyFile {
fn from_backend<B: ReadBackend>(be: &B, id: &KeyId) -> RusticResult<Self> {
let data = be.read_full(FileType::Key, id)?;

Ok(serde_json::from_slice(&data)
serde_json::from_slice(&data)
.map_err(
|err| KeyFileErrorKind::DeserializingFromSliceForKeyIdFailed {
key_id: id.clone(),
source: err,
},
)
.map_err(|_err| todo!("Error transition"))?)
.map_err(|_err| todo!("Error transition"))
}
}

Expand Down
29 changes: 29 additions & 0 deletions crates/core/tests/errors.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
use rstest::{fixture, rstest};
use std::backtrace::Backtrace;

use rustic_core::{ErrorKind, RusticError, Severity, Status};

#[fixture]
fn error() -> RusticError {
RusticError::new(
ErrorKind::Io,
"A file could not be read, make sure the file is existing and readable by the system.",
)
.status(Status::Permanent)
.severity(Severity::Error)
.code("E001".into())
.add_context("path", "/path/to/file")
.add_context("called", "used s3 backend")
.source(std::io::Error::new(std::io::ErrorKind::Other, "networking error").into())
.backtrace(Backtrace::disabled())
}

#[rstest]
fn test_error_display(error: RusticError) {
insta::assert_snapshot!(error);
}

#[rstest]
fn test_error_debug(error: RusticError) {
insta::assert_debug_snapshot!(error);
}
39 changes: 39 additions & 0 deletions crates/core/tests/snapshots/errors__error_debug.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
source: crates/core/tests/errors.rs
expression: error
---
RusticError {
kind: Io,
source: Some(
Custom {
kind: Other,
error: "networking error",
},
),
guidance: "A file could not be read, make sure the file is existing and readable by the system.",
context: [
(
"path",
"/path/to/file",
),
(
"called",
"used s3 backend",
),
],
docs_url: None,
code: Some(
"E001",
),
new_issue_url: None,
existing_issue_url: None,
severity: Some(
Error,
),
status: Some(
Permanent,
),
backtrace: Some(
<disabled>,
),
}
25 changes: 25 additions & 0 deletions crates/core/tests/snapshots/errors__error_display.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
---
source: crates/core/tests/errors.rs
expression: TEST_ERROR.to_string()
---
IO Error occurred in `rustic_core`

Message:
A file could not be read, make sure the file is existing and readable by the system.

Context:
path: /path/to/file,
called: used s3 backend

Caused by: networking error

Severity: Error

Status: Permanent

For more information, see: https://rustic.cli.rs/docs/errors/E001

If you think this is an undiscovered bug, please open an issue at: https://github.com/rustic-rs/rustic_core/issues/new

Backtrace:
<disabled>

0 comments on commit a28089d

Please sign in to comment.