Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Activity 26: Find the Bug with Tests

Problem 1 we'll do together during lecture. Problems 2 and 3 are at the end, on a laptop. You can keep this sheet, you'll just answer questions on Gradescope today.

Blackjack scoring, in case you've never played

Number cards are worth their number. Face cards (J, Q, K) are worth 10. An ace is worth 11, unless that would put the hand over 21, in which case it's worth 1. A hand over 21 is a bust. Exactly two cards worth 21 together is a blackjack.

Problem 1: Plan the tests (in lecture)

Four functions. You'll get the code later. For now you have the signatures and what each one promises, which is all a test needs.

/// The value of one card. Panics if `card` is not a card.
pub fn card_value(card: &str) -> u32

/// The value of a whole hand. An ace counts as 1 instead of 11 when it has to.
pub fn hand_value(hand: &[&str]) -> u32

/// True when the hand is worth more than 21.
pub fn is_bust(hand: &[&str]) -> bool

/// True for a blackjack: exactly two cards worth 21 together.
pub fn is_blackjack(hand: &[&str]) -> bool

Cards are strings: "A", "K", "Q", "J", "10", "9", down to "2". A hand is a slice of them, so a call looks like hand_value(&["A", "K"]).

For each of the last three functions, plan two tests: one ordinary hand, and one hand at an edge. Ask what could go wrong. An ace that has to count as 1? A total of exactly 21? Three cards that add up to 21? Write the hand and what the function should return. The last column waits for Problem 2.

FunctionWhichHandExpectedPass?
hand_valueordinary
hand_valueedge
is_bustordinary
is_bustedge
is_blackjackordinary
is_blackjackedge
card_valuebonus: not a card
panics

Problem 2: Write them and run them

  1. Open the link on the screen. It isn't on the website.
  2. The whole program is one file. At the bottom is a tests module with use super::* and one test already in it. Yours go under it.
  3. Type your six tests from the sheet. Give each a name that says what it checks, so a failure reads like a sentence.
  4. Click Test. The playground sees #[test] and runs cargo test instead of main.
  5. Fill in the Pass column on your sheet.
#[test]
fn king_and_five_is_fifteen() {
    assert_eq!(hand_value(&["K", "5"]), 15);
}

Problem 3: Find the bug

At least one test should have failed.

Which function is wrong, and why? If every test passed, your edges weren't edgy enough. Ask your neighbor for ideas if they got tests to fail.

Hand in

On Gradescope, before the end of class:

  1. One test you wrote for an ordinary hand.
  2. One test you wrote for an edge case.
  3. Which function(s) had a bug?

Solutions

  • Bug 1: hand_value changes an ace to 1 only if the hand is already busting when the ace is dealt. ["A", "K", "5"] = 26, should be 16. ["K", "5", "A"] = 16 is correct, so order matters
  • Bug 2: is_blackjack never checks the card count. ["7", "7", "7"] is 21 and reports blackjack
  • is_bust is correct
  • card_value("Joker") panics with not a card, for #[should_panic(expected = "not a card")]
  • Empty hand = 0, no panic
  • Fix 1: count aces in the loop, then while total > 21 && aces > 0 { total -= 10; aces -= 1; }
  • Fix 2: hand.len() == 2 && hand_value(hand) == 21

The fixed file with the added tests:

// Blackjack scoring.
//
// Number cards are worth their number and face cards are worth 10.
// An ace is worth 11, unless that would push the hand over 21, in which
// case it is worth 1. A hand is bust when it is over 21. A blackjack is
// a hand of exactly two cards worth 21.
//
// Cards are written as strings: "A", "K", "Q", "J", "10", "9", ... "2".
//
// Fixed version: both bugs repaired.

/// The value of one card. Panics if `card` is not a card.
pub fn card_value(card: &str) -> u32 {
    match card {
        "A" => 11,
        "K" | "Q" | "J" | "10" => 10,
        "9" => 9,
        "8" => 8,
        "7" => 7,
        "6" => 6,
        "5" => 5,
        "4" => 4,
        "3" => 3,
        "2" => 2,
        _ => panic!("not a card: {}", card),
    }
}

/// The value of a whole hand. An ace counts as 1 instead of 11 when it has to.
pub fn hand_value(hand: &[&str]) -> u32 {
    let mut total = 0;
    let mut aces = 0;
    for card in hand {
        total += card_value(card);
        if *card == "A" {
            aces += 1;
        }
    }
    while total > 21 && aces > 0 {
        total -= 10;
        aces -= 1;
    }
    total
}

/// True when the hand is worth more than 21.
pub fn is_bust(hand: &[&str]) -> bool {
    hand_value(hand) > 21
}

/// True for a blackjack: exactly two cards worth 21 together.
pub fn is_blackjack(hand: &[&str]) -> bool {
    hand.len() == 2 && hand_value(hand) == 21
}

// The six planned tests plus the two bonus ones. Paste over the `tests`
// module in src/lib.rs to see which fail against the planted bugs, or
// into solution/lib.rs to see them all pass.
#[cfg(test)]
mod tests {
    use super::*;

    // hand_value
    #[test]
    fn king_and_five_is_fifteen() {
        assert_eq!(hand_value(&["K", "5"]), 15);
    }

    #[test]
    fn ace_counts_as_one_when_eleven_would_bust() {
        assert_eq!(hand_value(&["A", "K", "5"]), 16, "the ace should drop to 1");
    }

    // is_bust
    #[test]
    fn twenty_five_is_bust() {
        assert!(is_bust(&["K", "9", "6"]));
    }

    #[test]
    fn exactly_twenty_one_is_not_bust() {
        assert!(!is_bust(&["K", "9", "2"]));
    }

    // is_blackjack
    #[test]
    fn ace_and_king_is_blackjack() {
        assert!(is_blackjack(&["A", "K"]));
    }

    #[test]
    fn three_sevens_is_twenty_one_but_not_blackjack() {
        assert!(!is_blackjack(&["7", "7", "7"]));
    }

    // bonus
    #[test]
    fn empty_hand_is_worth_zero() {
        assert_eq!(hand_value(&[]), 0);
    }

    #[test]
    #[should_panic(expected = "not a card")]
    fn joker_is_not_a_card() {
        card_value("Joker");
    }
}