26

I am writing pytest unit tests for the following function

from datetime import datetime

def validate_timestamp(timestamp):
    """Confirm that the passed in string is in the proper format %Y%m%d_%H"""
    try:
        ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
    except:
        raise ValueError("{0} must be in the format `%Y%m%d_%H".format(timestamp))
    return datetime.strftime(ts,'%Y%m%d_%H')

How would I test a malformed timestamp? what would be the best unit tests to write for this?

Marius Mucenicu
  • 1,685
  • 2
  • 16
  • 25
sakurashinken
  • 3,940
  • 8
  • 34
  • 67
  • 1
    Possible duplicate of [How to properly assert that exception raises in pytest?](http://stackoverflow.com/questions/23337471/how-to-properly-assert-that-exception-raises-in-pytest) – Lorenzo Belli Jan 13 '17 at 09:00

2 Answers2

41

Run the code that is expected to raise an exception in a with block like:

with pytest.raises(ValueError):
    # code

For details and options please read https://pytest.org/en/latest/getting-started.html#assert-that-a-certain-exception-is-raised .

Klaus D.
  • 13,874
  • 5
  • 41
  • 48
2

From Python 3.1, you can use the match argument to match entire or subtrings within the call stack.

from datetime import datetime

def validate_timestamp(timestamp):
    """Confirm that the passed in string is in the proper format %Y%m%d_%H"""
    try:
        ts = datetime.strptime(str(timestamp),'%Y%m%d_%H')
    except:
        raise ValueError("{0} must be in the format `%Y%m%d_%H".format(timestamp))
    return datetime.strftime(ts,'%Y%m%d_%H')

def test_bad_timestamp_fails():
    with pytest.raises(ValueError, match=r"foobar must be in the format `%Y%m%d_%H"):
                       validate_timestamp("foobar")
M_Merciless
  • 379
  • 6
  • 12