DEV Community

Cover image for Introduction To Testing By Writing A Simple Maths Lib
Abdur-Rahmaan Janhangeer
Abdur-Rahmaan Janhangeer

Posted on

Introduction To Testing By Writing A Simple Maths Lib

At one time or the other, testing becomes a need. You can't afford to ship parts not working so ... you test to ensure that everything is as intended. You don't only test codes but also guis, apis and database functioning. In this post we'll be sailing in shallow waters to enable beginners to start testing, once for all.

Our Maths Lib

Let us write a maths lib to solve common maths issues

  • area of square
  • area of triangle
  • length of hypotenuse

for the name i've chosen complemaths as it complements the standard library

Let us write our class

class Complemaths:

    def area_square(length_, width_):
        return width_ * length_

    def area_triangle(base_, height_):
        return base_ * height_ * 0.5

    def hypotenuse(side1_, side2_):
        return sqrt(side1_**2 + side2_**2)
  • 1 we did not add a constructor here as it was not needed.
  • 2 also, side1_**2 could have been side1_*side1_
  • 3 area_triangle and hypotenuse return floats

let us use our lib


print(Complemaths.area_square(2, 2))
print(Complemaths.area_triangle(5, 2))
print(Complemaths.hypotenuse(5, 5))

gives out


An Overview Of Testing

It's not really necessary to have a framework. You can do something like that:

def testing():
    if(Complemaths.area_square(2, 2) == 4):
        print('test1 ok')
        print('test1 fail')


or use assert

def test_area_square():
    assert Complemaths.area_square(2, 2) == 4, 'should be 4'


if all ok, no messages is displayed, else halts execution

but, a framework has some advanced capabilities. fortunately, python ships with it's own called unittesting, inspired by java's Junit

Our Test With Unittesting

class ComplemathsTests(unittest.TestCase):
    def test_area_square(self):
        self.assertEqual(Complemaths.area_square(5, 2), 10)

    def test_area_triangle(self):
        self.assertEqual(Complemaths.area_triangle(5, 2), 5.0)

    def test_hypotenuse(self):
        self.assertEqual(Complemaths.hypotenuse(3, 4), 5.0)

if __name__ == '__main__':

it gives us

Ran 3 tests in 0.001s


testing by parts is called unit testing and using tests in your development is called test driven development, tdd.

Photo by Malcolm Lightbody on Unsplash

Top comments (0)