Command Palette

Search for a command to run...

Hectal
Phase 11: Testing and Code Quality
Python · Exercise 6 of 6 Previous
Intermediate

Red, green: build a duration parser from a test table

Write parse_duration(text) that turns strings like "90s", "2m", "1h30m" into a number of seconds. Units are h (3600), m (60) and s (1). A string may have several parts, in any order, and the parts are added together. A string that contains a space is invalid.

Invalid text must raise ValueError: an empty string, text with no unit like "45", text with an unknown unit like "5x", or extra characters like "1h 30m".

This is TDD: the table of cases is already written and the program prints a result for each one. Make every line say ok.

What Check tests

  1. parse_duration("90s") is 90 and "2m" is 120
  2. parse_duration("1h30m") is 5400
  3. Parts can come in any order and repeat units add up
  4. Invalid text raises ValueError
  5. The program prints no FAIL line

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.