Introduction To Testing By Writing A Simple Maths Lib
Abdur-Rahmaan Janhangeer
Posted on February 18, 2019
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
Usage
print(Complemaths.area_square(2, 2))
print(Complemaths.area_triangle(5, 2))
print(Complemaths.hypotenuse(5, 5))
gives out
4
5.0
7.0710678118654755
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')
else:
print('test1 fail')
testing()
or use assert
def test_area_square():
assert Complemaths.area_square(2, 2) == 4, 'should be 4'
test_area_square()
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__':
unittest.main()
it gives us
...
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
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
Posted on February 18, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.