frontmatter_gen/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
//! Error handling for the frontmatter-gen crate.
//!
//! This module provides a comprehensive set of error types to handle various
//! failure scenarios that may occur during front matter parsing, conversion,
//! and extraction operations. Each error variant includes detailed error
//! messages and context to aid in debugging and error handling.
//!
//! # Error Handling Strategies
//!
//! The error system provides several ways to handle errors:
//!
//! - **Context-aware errors**: Use `Context` to add line/column information
//! - **Categorized errors**: Group errors by type using `Category`
//! - **Error conversion**: Convert from standard errors using `From` implementations
//! - **Rich error messages**: Detailed error descriptions with context
//!
//! # Features
//!
//! - Type-safe error handling with descriptive messages
//! - Support for YAML, TOML, and JSON parsing errors
//! - Content validation errors with size and depth checks
//! - Format-specific error handling
//! - Extraction and conversion error handling
//!
//! # Examples
//!
//! ```rust
//! use frontmatter_gen::error::Error;
//!
//! fn example() -> Result<(), Error> {
//!     // Example of handling YAML parsing errors
//!     let invalid_yaml = "invalid: : yaml";
//!     match serde_yml::from_str::<serde_yml::Value>(invalid_yaml) {
//!         Ok(_) => Ok(()),
//!         Err(e) => Err(Error::YamlParseError { source: e.into() }),
//!     }
//! }
//! ```

use serde_json::Error as JsonError;
use serde_yml::Error as YamlError;
use std::sync::Arc;
use thiserror::Error;

/// Provides additional context for front matter errors.
#[derive(Debug, Clone)]
pub struct Context {
    /// Line number where the error occurred.
    pub line: Option<usize>,
    /// Column number where the error occurred.
    pub column: Option<usize>,
    /// Snippet of the content where the error occurred.
    pub snippet: Option<String>,
}

impl std::fmt::Display for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "at {}:{}",
            self.line.unwrap_or(0),
            self.column.unwrap_or(0)
        )?;
        if let Some(snippet) = &self.snippet {
            write!(f, " near '{}'", snippet)?;
        }
        Ok(())
    }
}

/// Represents errors that can occur during front matter operations.
///
/// This enumeration uses the `thiserror` crate to provide structured error
/// messages, improving the ease of debugging and handling errors encountered
/// in front matter processing.
///
/// Each variant represents a specific type of error that may occur during
/// front matter operations, with appropriate context and error details.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
    /// Content exceeds the maximum allowed size.
    ///
    /// This error occurs when the content size is larger than the configured
    /// maximum limit.
    ///
    /// # Fields
    ///
    /// * `size` - The actual size of the content
    /// * `max` - The maximum allowed size
    #[error("Your front matter contains too many fields ({size}). The maximum allowed is {max}.")]
    ContentTooLarge {
        /// The actual size of the content
        size: usize,
        /// The maximum allowed size
        max: usize,
    },

    /// Nesting depth exceeds the maximum allowed.
    ///
    /// This error occurs when the structure's nesting depth is greater than
    /// the configured maximum depth.
    #[error(
        "Your front matter is nested too deeply ({depth} levels). The maximum allowed nesting depth is {max}."
    )]
    NestingTooDeep {
        /// The actual nesting depth
        depth: usize,
        /// The maximum allowed depth
        max: usize,
    },

    /// Error occurred whilst parsing YAML content.
    ///
    /// This error occurs when the YAML parser encounters invalid syntax or
    /// structure.
    #[error("Failed to parse YAML: {source}")]
    YamlParseError {
        /// The original error from the YAML parser
        source: Arc<YamlError>,
    },

    /// Error occurred whilst parsing TOML content.
    ///
    /// This error occurs when the TOML parser encounters invalid syntax or
    /// structure.
    #[error("Failed to parse TOML: {0}")]
    TomlParseError(#[from] toml::de::Error),

    /// Error occurred whilst parsing JSON content.
    ///
    /// This error occurs when the JSON parser encounters invalid syntax or
    /// structure.
    #[error("Failed to parse JSON: {0}")]
    JsonParseError(Arc<JsonError>),

    /// The front matter format is invalid or unsupported.
    ///
    /// This error occurs when the front matter format cannot be determined or
    /// is not supported by the library.
    #[error("Invalid front matter format")]
    InvalidFormat,

    /// Error occurred during conversion between formats.
    ///
    /// This error occurs when converting front matter from one format to another
    /// fails.
    #[error("Failed to convert front matter: {0}")]
    ConversionError(String),

    /// Generic error during parsing.
    ///
    /// This error occurs when a parsing operation fails with a generic error.
    #[error("Failed to parse front matter: {0}")]
    ParseError(String),

    /// Unsupported or unknown front matter format was detected.
    ///
    /// This error occurs when an unsupported front matter format is encountered
    /// at a specific line.
    #[error("Unsupported front matter format detected at line {line}")]
    UnsupportedFormat {
        /// The line number where the unsupported format was encountered
        line: usize,
    },

    /// No front matter content was found.
    ///
    /// This error occurs when attempting to extract front matter from content
    /// that does not contain any front matter section.
    #[error("No front matter found in the content")]
    NoFrontmatterFound,

    /// Invalid JSON front matter.
    ///
    /// This error occurs when the JSON front matter is malformed or invalid.
    #[error(
        "Invalid JSON front matter: malformed or invalid structure."
    )]
    InvalidJson,

    /// Invalid URL format.
    ///
    /// This error occurs when an invalid URL is encountered in the front matter.
    #[error(
        "Invalid URL: {0}. Ensure the URL is well-formed and valid."
    )]
    InvalidUrl(String),

    /// Invalid TOML front matter.
    ///
    /// This error occurs when the TOML front matter is malformed or invalid.
    #[error(
        "Invalid TOML front matter: malformed or invalid structure."
    )]
    InvalidToml,

    /// Invalid YAML front matter.
    ///
    /// This error occurs when the YAML front matter is malformed or invalid.
    #[error(
        "Invalid YAML front matter: malformed or invalid structure."
    )]
    InvalidYaml,

    /// Invalid language code.
    ///
    /// This error occurs when an invalid language code is encountered in the
    /// front matter.
    #[error("Invalid language code: {0}")]
    InvalidLanguage(String),

    /// JSON front matter exceeds maximum nesting depth.
    ///
    /// This error occurs when the JSON front matter structure exceeds the
    /// maximum allowed nesting depth.
    #[error("JSON front matter exceeds maximum nesting depth")]
    JsonDepthLimitExceeded,

    /// Error during front matter extraction.
    ///
    /// This error occurs when there is a problem extracting front matter from
    /// the content.
    #[error("Extraction error: {0}")]
    ExtractionError(String),

    /// Serialization or deserialization error.
    ///
    /// This error occurs when there is a problem serializing or deserializing
    /// content.
    #[error("Serialization or deserialization error: {source}")]
    SerdeError {
        /// The original error from the serde library
        source: Arc<serde_json::Error>,
    },

    /// Input validation error.
    ///
    /// This error occurs when the input fails validation checks.
    #[error("Input validation error: {0}")]
    ValidationError(String),

    /// Generic error with a custom message.
    ///
    /// This error occurs when a generic error is encountered with a custom message.
    #[error("Generic error: {0}")]
    Other(String),
}

impl Clone for Error {
    fn clone(&self) -> Self {
        match self {
            Self::ContentTooLarge { size, max } => {
                Self::ContentTooLarge {
                    size: *size,
                    max: *max,
                }
            }
            Self::NestingTooDeep { depth, max } => {
                Self::NestingTooDeep {
                    depth: *depth,
                    max: *max,
                }
            }
            Self::YamlParseError { source } => Self::YamlParseError {
                source: Arc::clone(source),
            },
            Self::JsonParseError(err) => {
                Self::JsonParseError(Arc::<serde_json::Error>::clone(
                    err,
                ))
            }
            Self::TomlParseError(err) => {
                Self::TomlParseError(err.clone())
            }
            Self::SerdeError { source } => Self::SerdeError {
                source: Arc::clone(source),
            },
            Self::ConversionError(msg) => {
                Self::ConversionError(msg.clone())
            }
            Self::ParseError(msg) => Self::ParseError(msg.clone()),
            Self::UnsupportedFormat { line } => {
                Self::UnsupportedFormat { line: *line }
            }
            Self::NoFrontmatterFound => Self::NoFrontmatterFound,
            Self::InvalidJson => Self::InvalidJson,
            Self::InvalidToml => Self::InvalidToml,
            Self::InvalidYaml => Self::InvalidYaml,
            Self::JsonDepthLimitExceeded => {
                Self::JsonDepthLimitExceeded
            }
            Self::ExtractionError(msg) => {
                Self::ExtractionError(msg.clone())
            }
            Self::ValidationError(msg) => {
                Self::ValidationError(msg.clone())
            }
            Self::InvalidUrl(msg) => Self::InvalidUrl(msg.clone()),
            Self::InvalidLanguage(msg) => {
                Self::InvalidLanguage(msg.clone())
            }
            Self::Other(msg) => Self::Other(msg.clone()),
            Self::InvalidFormat => Self::InvalidFormat,
        }
    }
}

/// Categories of front matter errors.
///
/// This enumeration defines the main categories of errors that can occur
/// during front matter operations.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Category {
    /// Parsing-related errors.
    Parsing,
    /// Validation-related errors.
    Validation,
    /// Conversion-related errors.
    Conversion,
    /// Configuration-related errors.
    Configuration,
}

impl Error {
    /// Returns the category of the error.
    ///
    /// # Returns
    ///
    /// Returns the `Category` that best describes this error.
    #[must_use]
    pub const fn category(&self) -> Category {
        match self {
            Self::YamlParseError { .. }
            | Self::TomlParseError(_)
            | Self::JsonParseError(_)
            | Self::SerdeError { .. }
            | Self::ParseError(_)
            | Self::InvalidFormat
            | Self::UnsupportedFormat { .. }
            | Self::NoFrontmatterFound
            | Self::InvalidJson
            | Self::InvalidToml
            | Self::InvalidYaml
            | Self::JsonDepthLimitExceeded
            | Self::ExtractionError(_)
            | Self::InvalidUrl(_)
            | Self::InvalidLanguage(_) => Category::Parsing,
            Self::ValidationError(_) => Category::Validation,
            Self::ConversionError(_) => Category::Conversion,
            Self::ContentTooLarge { .. }
            | Self::NestingTooDeep { .. }
            | Self::Other(_) => Category::Configuration,
        }
    }

    /// Creates a generic parse error with a custom message.
    ///
    /// # Arguments
    ///
    /// * `message` - A string slice containing the error message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use frontmatter_gen::error::Error;
    ///
    /// let error = Error::generic_parse_error("Invalid syntax");
    /// assert!(matches!(error, Error::ParseError(_)));
    /// ```
    #[must_use]
    pub fn generic_parse_error(message: &str) -> Self {
        Self::ParseError(message.to_string())
    }

    /// Creates an unsupported format error for a specific line.
    ///
    /// # Arguments
    ///
    /// * `line` - The line number where the unsupported format was detected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use frontmatter_gen::error::Error;
    ///
    /// let error = Error::unsupported_format(42);
    /// assert!(matches!(error, Error::UnsupportedFormat { line: 42 }));
    /// ```
    #[must_use]
    pub const fn unsupported_format(line: usize) -> Self {
        Self::UnsupportedFormat { line }
    }

    /// Creates a validation error with a custom message.
    ///
    /// # Arguments
    ///
    /// * `message` - A string slice containing the validation error message.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use frontmatter_gen::error::Error;
    ///
    /// let error = Error::validation_error("Invalid character in title");
    /// assert!(matches!(error, Error::ValidationError(_)));
    /// ```
    #[must_use]
    pub fn validation_error(message: &str) -> Self {
        Self::ValidationError(message.to_string())
    }

    /// Adds context to an error.
    ///
    /// # Arguments
    ///
    /// * `context` - Additional context information about the error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use frontmatter_gen::error::{Error, Context};
    ///
    /// let context = Context {
    ///     line: Some(42),
    ///     column: Some(10),
    ///     snippet: Some("invalid content".to_string()),
    /// };
    ///
    /// let error = Error::ParseError("Invalid syntax".to_string())
    ///     .with_context(&context);
    /// ```
    #[must_use]
    pub fn with_context(self, context: &Context) -> Self {
        let context_info = format!(
            " (line: {}, column: {})",
            context.line.unwrap_or(0),
            context.column.unwrap_or(0)
        );
        let snippet_info = context
            .snippet
            .as_ref()
            .map(|s| format!(" near '{}'", s))
            .unwrap_or_default();

        match self {
            Self::ParseError(msg) => Self::ParseError(format!(
                "{msg}{context_info}{snippet_info}"
            )),
            Self::YamlParseError { source } => {
                Self::YamlParseError { source }
            }
            _ => self, // For unsupported variants
        }
    }
}

/// Errors that can occur during site generation.
///
/// This enum is used to represent higher-level errors encountered during site
/// generation processes, such as template rendering, file system operations,
/// and metadata processing.
#[derive(Error, Debug)]
pub enum EngineError {
    /// Error occurred during content processing.
    #[error("Content processing error: {0}")]
    ContentError(String),

    /// Error occurred during template processing.
    #[error("Template processing error: {0}")]
    TemplateError(String),

    /// Error occurred during asset processing.
    #[error("Asset processing error: {0}")]
    AssetError(String),

    /// Error occurred during file system operations.
    #[error("File system error: {source}")]
    FileSystemError {
        /// The original IO error that caused this error.
        source: std::io::Error,
        /// Additional context information about the error.
        context: String,
    },

    /// Error occurred during metadata processing.
    #[error("Metadata error: {0}")]
    MetadataError(String),
}

impl Clone for EngineError {
    fn clone(&self) -> Self {
        match self {
            Self::ContentError(msg) => Self::ContentError(msg.clone()),
            Self::TemplateError(msg) => {
                Self::TemplateError(msg.clone())
            }
            Self::AssetError(msg) => Self::AssetError(msg.clone()),
            Self::FileSystemError { source, context } => {
                Self::FileSystemError {
                    source: std::io::Error::new(
                        source.kind(),
                        source.to_string(),
                    ),
                    context: context.clone(),
                }
            }
            Self::MetadataError(msg) => {
                Self::MetadataError(msg.clone())
            }
        }
    }
}

/// Converts an `EngineError` into an `Error`.
///
/// This allows engine errors to be converted into front matter errors when needed,
/// preserving the error context and message.
///
/// # Examples
///
/// ```rust
/// use frontmatter_gen::error::{EngineError, Error};
/// use std::io;
///
/// let engine_error = EngineError::ContentError("content processing failed".to_string());
/// let frontmatter_error: Error = engine_error.into();
/// assert!(matches!(frontmatter_error, Error::ParseError(_)));
/// ```
impl From<EngineError> for Error {
    fn from(err: EngineError) -> Self {
        match err {
            EngineError::ContentError(msg) => {
                Self::ParseError(format!("Content error: {}", msg))
            }
            EngineError::TemplateError(msg) => {
                Self::ParseError(format!("Template error: {}", msg))
            }
            EngineError::AssetError(msg) => {
                Self::ParseError(format!("Asset error: {}", msg))
            }
            EngineError::FileSystemError { source, context } => {
                Self::ParseError(format!(
                    "File system error: {} ({})",
                    source, context
                ))
            }
            EngineError::MetadataError(msg) => {
                Self::ParseError(format!("Metadata error: {}", msg))
            }
        }
    }
}

/// Converts an IO error (`std::io::Error`) into a front matter `Error`.
impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        Self::ParseError(err.to_string())
    }
}

/// Converts a front matter `Error` into a string.
impl From<Error> for String {
    fn from(err: Error) -> Self {
        err.to_string()
    }
}

#[cfg(test)]
mod tests {
    /// Tests for the `Error` enum and its associated methods.
    mod error_tests {
        use super::super::*;

        /// Test the `ContentTooLarge` error variant.
        #[test]
        fn test_content_too_large_error() {
            let error = Error::ContentTooLarge {
                size: 1000,
                max: 500,
            };
            assert_eq!(
                error.to_string(),
                "Your front matter contains too many fields (1000). The maximum allowed is 500."
            );
        }

        /// Test the `NestingTooDeep` error variant.
        #[test]
        fn test_nesting_too_deep_error() {
            let error = Error::NestingTooDeep { depth: 10, max: 5 };
            assert_eq!(
                error.to_string(),
                "Your front matter is nested too deeply (10 levels). The maximum allowed nesting depth is 5."
            );
        }

        /// Test the `JsonParseError` error variant.
        #[test]
        fn test_json_parse_error() {
            let json_data = r#"{"key": invalid}"#;
            let result: Result<serde_json::Value, _> =
                serde_json::from_str(json_data);
            assert!(result.is_err());
            let error =
                Error::JsonParseError(Arc::new(result.unwrap_err()));
            assert!(matches!(error, Error::JsonParseError(_)));
        }

        /// Test the `InvalidFormat` error variant.
        #[test]
        fn test_invalid_format_error() {
            let error = Error::InvalidFormat;
            assert_eq!(
                error.to_string(),
                "Invalid front matter format"
            );
        }

        /// Test the `ConversionError` error variant.
        #[test]
        fn test_conversion_error() {
            let error =
                Error::ConversionError("Conversion failed".to_string());
            assert_eq!(
                error.to_string(),
                "Failed to convert front matter: Conversion failed"
            );
        }

        /// Test the `UnsupportedFormat` error variant.
        #[test]
        fn test_unsupported_format() {
            let error = Error::unsupported_format(42);
            assert!(matches!(
                error,
                Error::UnsupportedFormat { line: 42 }
            ));
            assert_eq!(
                error.to_string(),
                "Unsupported front matter format detected at line 42"
            );
        }

        /// Test the `NoFrontmatterFound` error variant.
        #[test]
        fn test_no_frontmatter_found() {
            let error = Error::NoFrontmatterFound;
            assert_eq!(
                error.to_string(),
                "No front matter found in the content"
            );
        }

        /// Test the `InvalidJson` error variant.
        #[test]
        fn test_invalid_json_error() {
            let error = Error::InvalidJson;
            assert_eq!(error.to_string(), "Invalid JSON front matter: malformed or invalid structure.");
        }

        /// Test the `InvalidUrl` error variant.
        #[test]
        fn test_invalid_url_error() {
            let error =
                Error::InvalidUrl("http:// invalid.url".to_string());
            assert_eq!(
                error.to_string(),
                "Invalid URL: http:// invalid.url. Ensure the URL is well-formed and valid."
            );
        }

        /// Test the `InvalidYaml` error variant.
        #[test]
        fn test_invalid_yaml_error() {
            let error = Error::InvalidYaml;
            assert_eq!(
                error.to_string(),
                "Invalid YAML front matter: malformed or invalid structure."
            );
        }

        /// Test the `ValidationError` error variant.
        #[test]
        fn test_validation_error() {
            let error =
                Error::ValidationError("Invalid title".to_string());
            assert_eq!(
                error.to_string(),
                "Input validation error: Invalid title"
            );
        }

        /// Test the `JsonDepthLimitExceeded` error variant.
        #[test]
        fn test_json_depth_limit_exceeded() {
            let error = Error::JsonDepthLimitExceeded;
            assert_eq!(
                error.to_string(),
                "JSON front matter exceeds maximum nesting depth"
            );
        }

        /// Test the `category` method for different error variants.
        #[test]
        fn test_category_method() {
            let validation_error =
                Error::ValidationError("Invalid field".to_string());
            assert_eq!(
                validation_error.category(),
                Category::Validation
            );

            let conversion_error =
                Error::ConversionError("Conversion failed".to_string());
            assert_eq!(
                conversion_error.category(),
                Category::Conversion
            );

            let config_error =
                Error::ContentTooLarge { size: 100, max: 50 };
            assert_eq!(
                config_error.category(),
                Category::Configuration
            );
        }

        /// Test the `Clone` implementation for `Error`.
        #[test]
        fn test_error_clone() {
            let original = Error::ContentTooLarge {
                size: 200,
                max: 100,
            };
            let cloned = original.clone();
            assert!(
                matches!(cloned, Error::ContentTooLarge { size, max } if size == 200 && max == 100)
            );
        }
    }

    /// Tests for the `EngineError` enum.
    mod engine_error_tests {
        use super::super::*;
        use std::io;

        /// Test the `ContentError` variant.
        #[test]
        fn test_content_error() {
            let error = EngineError::ContentError(
                "Processing failed".to_string(),
            );
            assert_eq!(
                error.to_string(),
                "Content processing error: Processing failed"
            );
        }

        /// Test `EngineError::FileSystemError` conversion to `Error`.
        #[test]
        fn test_engine_error_to_error_conversion() {
            let io_error =
                io::Error::new(io::ErrorKind::Other, "disk full");
            let engine_error = EngineError::FileSystemError {
                source: io_error,
                context: "Saving file".to_string(),
            };
            let converted: Error = engine_error.into();
            assert!(converted.to_string().contains("disk full"));
            assert!(converted.to_string().contains("Saving file"));
        }
    }

    /// Tests for the `Context` struct.
    mod context_tests {
        use super::super::*;

        /// Test the `Display` implementation of `Context`.
        #[test]
        fn test_context_display() {
            let context = Context {
                line: Some(42),
                column: Some(10),
                snippet: Some("invalid key".to_string()),
            };
            assert_eq!(
                context.to_string(),
                "at 42:10 near 'invalid key'"
            );
        }

        /// Test missing fields in `Context`.
        #[test]
        fn test_context_missing_fields() {
            let context = Context {
                line: None,
                column: None,
                snippet: Some("example snippet".to_string()),
            };
            assert_eq!(
                context.to_string(),
                "at 0:0 near 'example snippet'"
            );
        }
    }

    /// Tests for conversions.
    mod conversion_tests {
        use super::super::*;
        use std::io;

        /// Test the conversion from `std::io::Error` to `Error`.
        #[test]
        fn test_io_error_conversion() {
            let io_error =
                io::Error::new(io::ErrorKind::NotFound, "file missing");
            let error: Error = io_error.into();
            assert!(matches!(error, Error::ParseError(_)));
            assert!(error.to_string().contains("file missing"));
        }
    }

    /// Test the conversion of `EngineError` to `Error`.
    #[test]
    fn test_engine_error_conversion() {
        let engine_error = crate::error::EngineError::ContentError(
            "content failed".to_string(),
        );
        let error: crate::Error = engine_error.into();
        assert!(matches!(error, crate::Error::ParseError(_)));
        assert!(error.to_string().contains("content failed"));
    }
}