Learn

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

1.

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:

  1. Call entertainment.get_maximum_display_brightness() and store the return value in a variable called brightness.

  2. Next, call self.assertAlmostEqual() to make sure that brightness is almost equal to 400.

2.

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:

  1. Call entertainment.get_device_temp() and store the return value in a variable called device_temp.

  2. Then call self.assertLess() to make sure that device_temp is less than 35.

The test should fail because the current temperature is 40.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?