This post has already been read 1174 times!

Circle Area using Python
from math import pi

def circle_area(r):
    if r < 0:
        raise ValueError("The radius cannot be negative")
    return pi*(r**2)
Unit Test for Python
import unittest
from circles import circle_area
from math import pi

class TestCircleArea(unittest.TestCase):
    def test_area(self):
        # test area when radius >= 0
        self.assertAlmostEqual(circle_area(1), pi)
        self.assertAlmostEqual(circle_area(0), 0)
        self.assertAlmostEqual(circle_area(2.1), pi * (2.1 ** 2))

    def test_values(self):
        # make sure value errors are raised when necessary
        self.assertRaises(ValueError, circle_area, -2)
Running the unit test
python -m unittest

Leave a Reply

Post Navigation