Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert ValueError in pytest

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?

like image 481
sakurashinken Avatar asked Jun 16 '16 22:06

sakurashinken


1 Answers

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 .

like image 67
Klaus D. Avatar answered Sep 28 '22 21:09

Klaus D.