Often we need to test conditions related to numbers. The unittest
module provides a handful of assert methods to achieve this. Let’s take a look at two common assert methods related to quantitative comparisons, their general syntax, as well as their assert
statement equivalents.
assertLess: The
assertLess()
method takes two arguments and checks that the first argument is less than the second one. If it is not, the test will fail.self.assertLess(value1, value2)assertAlmostEqual: The
assertAlmostEqual()
method takes two arguments and checks that their difference, when rounded to 7 decimal places, is 0. In other words, if they are almost equal. If the values are not close enough to equality, the test will fail.self.assertAlmostEqual(value1, value2)
The equivalent assert
statements would be the following:
Method | Equivalent |
---|---|
self.assertLess(2, 5) |
assert 2 < 5 |
self.assertAlmostEqual(.22, .225) |
assert round(.22 - .225, 7) == 0 |
The full list of quantitative methods can be seen in the Python documentation. Let’s put these methods into practice!
Instructions
Our entertainment.py
file has a function called get_maximum_display_brightness()
that returns the max screen brightness value.
Create a test method called test_maximum_display_brightness()
. Inside the method, do the following:
Call
entertainment.get_maximum_display_brightness()
and store the return value in a variable calledbrightness
.Next, call
self.assertAlmostEqual()
to make sure thatbrightness
is almost equal to400
.
Our entertainment.py
file has a method called entertainment.get_device_temp()
that returns the current device temperature.
Create a test method called test_device_temperature()
. Inside the method do the following:
Call
entertainment.get_device_temp()
and store the return value in a variable calleddevice_temp
.Then call
self.assertLess()
to make sure thatdevice_temp
is less than35
.
The test should fail because the current temperature is 40
.