From 9f2f6cffb37d7b48a952e349c9255568107b57e4 Mon Sep 17 00:00:00 2001 From: Gibson Fahnestock Date: Sun, 29 Jan 2017 15:09:44 +0000 Subject: [PATCH] luhn: Update example and add more tests The luhn test suite didn't cover a lot of cases, including: - Strings of zeros - Non-alphabetic characters - SINs which are only valid if you remember to reverse the string - A 9 in a doubled position (9 * 2 - 9 should equal 9 not 0) - " 0" (invalid as there's only 1 digit) This adds those tests and updates the example to properly reject symbols. --- exercises/luhn/example.rs | 3 ++- exercises/luhn/tests/luhn.rs | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/exercises/luhn/example.rs b/exercises/luhn/example.rs index da6c35021..e2eb42421 100644 --- a/exercises/luhn/example.rs +++ b/exercises/luhn/example.rs @@ -1,5 +1,6 @@ pub fn is_valid(candidate: &str) -> bool { - if candidate.chars().any(|c| c.is_alphabetic()) || candidate.chars().count() == 1 { + if candidate.chars().filter(|c| c.is_digit(10)).take(2).count() <= 1 || + candidate.chars().any(|c| !c.is_digit(10) && c != ' ') { return false; } diff --git a/exercises/luhn/tests/luhn.rs b/exercises/luhn/tests/luhn.rs index bcf809e5e..7a400f3e5 100644 --- a/exercises/luhn/tests/luhn.rs +++ b/exercises/luhn/tests/luhn.rs @@ -13,6 +13,12 @@ fn single_zero_string_is_invalid() { assert!(!is_valid("0")); } +#[test] +#[ignore] +fn simple_valid_sin() { + assert!(is_valid(" 5 9 ")); +} + #[test] #[ignore] fn valid_canadian_sin_is_valid() { @@ -36,3 +42,39 @@ fn invalid_credit_card_is_invalid() { fn strings_that_contain_non_digits_are_invalid() { assert!(!is_valid("046a 454 286")); } + +#[test] +#[ignore] +fn punctuation_is_invalid() { + assert!(!is_valid("055-444-285")); +} + +#[test] +#[ignore] +fn symbols_are_invalid() { + assert!(!is_valid("055£ 444$ 285")); +} + +#[test] +#[ignore] +fn single_digit_with_space_is_invalid() { + assert!(!is_valid(" 0")); +} + +#[test] +#[ignore] +fn lots_of_zeros_are_valid() { + assert!(is_valid(" 00000")); +} + +#[test] +#[ignore] +fn another_valid_sin() { + assert!(is_valid("055 444 285")); +} + +#[test] +#[ignore] +fn nine_doubled_is_nine() { + assert!(is_valid("091")); +}