My code after running through Jeff Knopp’s unittest tutorial

Ran through Jeff Knopp’s unittest tutorial, which I recommend. This post documents the code I ended up with.

This class–the one to be tested–is the same:

def is_prime(number):
      Is the provided number divisible by any number between two and itself?
   if  number < 0:
      return  False

   for  element in range(2, number):
      if  number % element == 0:
         return  False

   # number is not divisible by anything between 2 and itself
   return  True

The testing class, though, is different. Just tailored to my style:

import unittest
from prime_number_util import is_prime

class PrimesTestCase(unittest.TestCase):
        Tests for prime_number_util.is_prime()

    def test__prime_numbers__zero_through_seven(self):
           Testing all prime numbers, starting with zero, ending with seven.
        self.assert_is_prime(True, 0)
        self.assert_is_prime(True, 1)
        self.assert_is_prime(True, 2)
        self.assert_is_prime(True, 3)
        self.assert_is_prime(True, 5)
        self.assert_is_prime(True, 7)

    def test__non_prime_numbers__negative(self):
           Testing negative numbers, which are never prime.
        self.assert_is_prime(False, -500)
        self.assert_is_prime(False, -5)
        self.assert_is_prime(False, -1)

    def test__non_prime_numbers__four_through_nine(self):
           Testing some positive prime numbers.
        self.assert_is_prime(False, 4)
        self.assert_is_prime(False, 6)
        self.assert_is_prime(False, 8)
        self.assert_is_prime(False, 9)

    def assert_is_prime(self, boolean_expected, number):
            Master function for is_prime testing.
        self.assertEqual(boolean_expected, is_prime(number))

if  __name__ == '__main__':

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s