Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using assertRaises unit test for date comparison

I’m trying to use assertRaises(ValueError) in Python to return an error when the start date of my code is after the end date.

class TestDateUtils(unittest.TestCase):
def test_date_range(self):
     start_date = datetime.date(2020, 1, 1)
     end_date = datetime.date(2020, 1, 1)
     expected = start_date < end_date
     actual = start_date > end_date

    with self.assertRaises(ValueError):
        if actual:
            raise ValueError
        else:
            expected
            print("all fine")

I’m new to Python (and this is probably nowhere near the correct way to write this).
Would anyone know the correct syntax for trying to produce this end result? I just want to raise a value error if my start date is after the end date.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The purpose of assertRaises is to test that an exception is raised by the code under test in a certain set of circumstances; it is not for raising a value error.

If you want to assert in a test case that one value is less than another, you can use assertLess or assertLessEqual.

E.g.

self.assertLess(end_date, start_date)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading