Calmcode - pytest: coverage


1 2 3 4 5 6 7 8 9 10 11

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.


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


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):

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


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