Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 655
cheesysam Avatar asked Sep 20 '11 09:09

cheesysam


People also ask

How do you assert multiple conditions in Python?

If you assert multiple conditions in a single assert statement, you only make the job harder. This is because you cannot determine which one of the conditions caused the bug. If you want to push it, you can assert multiple conditions similar to how you check multiple conditions in an if statement.

How do you check assert in Python?

The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.

Should you use assert in Python?

Python's assert statement is a debugging aid, not a mechanism for handling run-time errors. The goal of using assertions is to let developers find the likely root cause of a bug more quickly. An assertion error should never be raised unless there's a bug in your program.


1 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) 
like image 187
Frédéric Hamidi Avatar answered Sep 24 '22 04:09

Frédéric Hamidi