logo

... pytest.


Testing your code is a good idea because it usually leads to great improvements. There's many libraries in python that will help with testing but a favourable on called pytest. In this series of videos we demonstrate how the use it.


Episode Notes

You first need to install the coverage tools;

python -m pip install pytest-cov

And you should now be able to run the coverage command. By running this one you'll generate the html files too;

pytest --cov blackjack --cov-report html

You should see a new htmlcov folder that contains the index.html file that gives you the drilldown.

Fixes

We've also fixed files in this video. You can find them below.

tests/test_blackjack.py

import pytest

from blackjack.common import card_score

@pytest.mark.parametrize("cards,score", [("KK", 20), ("JKQ", 0), ("AK", 21), ("AA", 12)])
def test_simple_case(cards, score):
    assert card_score(cards) == score

def test_value_error_is_raised1():
    with pytest.raises(ValueError):
        card_score("")

def test_value_error_is_raised2():
    with pytest.raises(ValueError):
        card_score(1)

tests/test_blackjack.py

def card_score(cards):
  if not isinstance(cards, str):
      raise ValueError("The input for `card_score` needs to be a string.")
  if len(cards) < 2:
      raise ValueError("The `card_score` function requires at least 2 cards.")
  numbers = [c for c in cards if c in "23456789"]
  faces = [c for c in cards if c in "JQK"]
  n_aces = sum([1 for c in cards if c == "A"])
  score = sum([int(i) for i in numbers]) + len(faces) * 10
  while n_aces > 0:
      score += 1 if score + 11 > 21 else 11
      n_aces -= 1
  return score if score <= 21 else 0

Feedback? See an issue? Feel free to mention it here.

If you want to be kept up to date, consider getting the newsletter.