100-exercises-to-learn-rust/exercises/05_ticket_v2/06_fallibility/src/lib.rs

72 lines
2.0 KiB
Rust
Raw Normal View History

2024-05-13 04:21:03 +08:00
// TODO: Convert the `Ticket::new` method to return a `Result` instead of panicking.
// Use `String` as the error type.
#[derive(Debug, PartialEq)]
struct Ticket {
title: String,
description: String,
status: Status,
}
#[derive(Debug, PartialEq)]
enum Status {
ToDo,
InProgress { assigned_to: String },
Done,
}
impl Ticket {
pub fn new(title: String, description: String, status: Status) -> Ticket {
if title.is_empty() {
panic!("Title cannot be empty");
}
if title.len() > 50 {
panic!("Title cannot be longer than 50 characters");
}
if description.is_empty() {
panic!("Description cannot be empty");
}
if description.len() > 500 {
panic!("Description cannot be longer than 500 characters");
}
Ticket {
title,
description,
status,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use common::{overly_long_description, overly_long_title, valid_description, valid_title};
#[test]
fn title_cannot_be_empty() {
let error = Ticket::new("".into(), valid_description(), Status::ToDo).unwrap_err();
assert_eq!(error, "Title cannot be empty");
}
#[test]
fn description_cannot_be_empty() {
let error = Ticket::new(valid_title(), "".into(), Status::ToDo).unwrap_err();
assert_eq!(error, "Description cannot be empty");
}
#[test]
fn title_cannot_be_longer_than_fifty_chars() {
let error =
Ticket::new(overly_long_title(), valid_description(), Status::ToDo).unwrap_err();
assert_eq!(error, "Title cannot be longer than 50 characters");
}
#[test]
fn description_cannot_be_longer_than_500_chars() {
let error =
Ticket::new(valid_title(), overly_long_description(), Status::ToDo).unwrap_err();
assert_eq!(error, "Description cannot be longer than 500 characters");
}
}