Is there a python assert() method which checks between two boundaries?

Question:

In some unit testing I’m currently doing, I need to pass a test when a variable lies between two boundary conditions.

Something like –

def myTest(self):
    myInt = 5
    self.assertBetween(myInt,3,8)

would pass the test. Or if myInt lied outside of the range 3 to 8 it would fail.

I’ve looked down the list of assert methods in the python documentation and can’t work out which one would give me this sort of functionality.

Thanks.

Asked By: cheesysam

||

Answers:

You can use assertTrue() for that purpose:

self.assertTrue(myInt >= 3 and myInt <= 8)

Or, using Python’s comparison chaining idiom:

self.assertTrue(3 <= myInt <= 8)
Answered By: Frédéric Hamidi

Frédéric’s suggestion to use:

self.assertTrue(3 <= myInt <= 8)

results in test output like this:

AssertionError: False is not True

which gives the developer no clue as to what the problematic value of myInt actually was. It is better to be more long-winded:

self.assertGreaterEqual(myInt, 3)
self.assertLessEqual(myInt, 8)

because then you get helpful test output like this:

AssertionError: 21 not less than or equal to 8

If you find yourself using this idiom a lot, then you can write your own assertion method:

def assertBetween(self, value, min, max):
    """Fail if value is not between min and max (inclusive)."""
    self.assertGreaterEqual(value, min)
    self.assertLessEqual(value, max)

Note that if the value to be tested is known to be an integer, then you can use assertIn together with range:

self.assertIn(myInt, range(3, 9))

which results in test output like this:

AssertionError: 21 not found in range(3, 9)
Answered By: Gareth Rees

to complement the answer, you can add a msg to self.assertTrue and make it more readable

so

self.assertTrue(3 <= myInt <= 8, msg="%i is not between 3 and 8" % myInt)

would yield the right output and you wont need to do assertGreaterEqual and assertLessEqual.

Answered By: aleivag

There is assertAlmostEqual which main use case is to compare floating point numbers. But with the delta parameter you can use it for ints:

self.assertAlmostEqual(9, 5, delta=3)

And this gives you meaningful error message:

AssertionError: 9 != 5 within 3 delta
Answered By: fcs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.