Unittests

In this post we will start understanding an interesting topic in python
i.e Unit_tests and most important of all while developing any software is understanding the actual use-case and be clear with the tests
to be covered to verify the working of the use-case.

Unit tests are that type of tests which are not considered as functional tests rather, It is used to do some basic testing of python definitions by sending some fake parameters to the actual definitions in source code and assert the expected values

Say suppose now u have written a code to test whether a number is a prime or not
we send some random value and check whether we get the expected value or not.

So, our use-case is to check whether the number gave by user is prime or not?

So, the tests to be checked are
 - Composite numbers shouldn't be returned as prime.
 - Negative numbers mustnot be considered as a prime number.
 - check when a prime number is given by user it returns True.

mkdir test_1 && cd test_1


and create two files

#This is our source_code check_prime.py
def verify_prime(num):
    """Return True if *number* is prime."""
    if num <= 1:
        return False

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

    return True

we check the expected values or test our code like this..

-- in test_1 directory create another file test_check_prime.py with below contents

import unittest
import check_prime

class PrimesTestCase(unittest.TestCase):
    """Tests for `primes.py`."""

    def test_is_five_prime(self):
        """Is five successfully determined to be prime?"""
        self.assertTrue(check_prime.verify_prime(5))

    def test_prime_negative(self):
        """Is -1 successfully determined to be not prime?"""
        self.assertFalse(check_prime.verify_prime(-1))

    def test_is_six_prime(self):
        """Is six successfully determined to be composite?"""
        self.assertFalse(check_prime.verify_prime(6))

    def test_is_seven_prime(self):
        """Is seven successfully determined to be prime?"""
        self.assertTrue(check_prime.verify_prime(7))

if __name__ == '__main__':
    unittest.main()
This should be our expected value

-Inspiron-3542:~/python_exp$ nosetests -sv test_check_prime.py
Is five successfully determined to be prime? ... ok
Is seven successfully determined to be prime? ... ok
Is six successfully determined to be composite? ... ok
Is -1 successfully determined to be not prime? ... ok

----------------------------------------------------------------------
Ran 4 tests in 0.001s

OK

Comments

Post a Comment

Popular posts from this blog

Setup K8s to use nvidia drivers

Upgrade mongo from 3.x to 4.x