I am starting to explore automated testing of code, so I decided to write some trivial code about the cartesian plane and test it. I am particularly interested in automated testing conventions and tips.
cartesian.py
def pytagoras(a,b):
return (a**2 + b**2)**0.5
def distance(point_1,point_2):
return pytagoras((point_1[0]-point_2[0]),(point_1[1]-point_2[1]))
def point_in_line(point,line):
def function(x):
return line[0] * x + line[1]
return function(point[0]) == point[1]
def average(lst):
return sum(lst) / len(lst)
def middle_point(point_1,point_2):
return [average([point_1[0],point_2[0]]),average([point_1[1],point_2[1]])]
def is_valid_triangle(sides):
return sum(sides) - max(sides) > max(sides)
def heron(AB,BC,AC):
if not is_valid_triangle((AB,BC,AC)):
raise ValueError("The sides length given can't be a triangle.")
sp = sum([AB,BC,AC]) / 2
return (sp * (sp-AB) * (sp-BC) * (sp-AC) )**0.5
def area_of_tringle(points):
AB = distance(points[0],points[1])
BC = distance(points[1],points[2])
AC = distance(points[0],points[2])
return heron(AB,BC,AC)
test_cartesian.py
import unittest
import cartesian
class test_cartesian(unittest.TestCase):
def test_pytagoras(self):
self.assertEqual(cartesian.pytagoras(3,4),5)
self.assertEqual(cartesian.pytagoras(6,8),10)
def test_distance(self):
self.assertEqual(cartesian.distance( (0,0) , (3,4) ),5)
self.assertEqual(cartesian.distance( (1,2) , (4,6) ), 5)
self.assertEqual(cartesian.distance( (1,1) , (1,1) ),0)
def test_point_in_line(self):
self.assertTrue(cartesian.point_in_line([4,6],[1,2]))
self.assertTrue(cartesian.point_in_line([2,8],[3,2]))
def test_average(self):
self.assertEqual(cartesian.average([8,4,8,0]), 5)
def test_middle_point(self):
self.assertEqual(cartesian.middle_point([8,2],[0,4]),[4,3])
self.assertEqual(cartesian.middle_point([5,5],[7,13]),[6,9])
def is_valid_triangle(self):
self.assertFalse(cartesian.is_valid_triangle(2,4,100))
self.assertTrue(cartesian.is_valid_triangle(6,5,20))
def test_heron(self):
self.assertEqual(cartesian.heron(3,4,5),6)
self.assertAlmostEqual(cartesian.heron(3,6,8),7.64,places=2)
def test_area_of_triangle(self):
self.assertAlmostEqual(cartesian.area_of_tringle(([4,2],[6,2],[7,0])),2)
self.assertAlmostEqual(cartesian.area_of_tringle(([4,1],[3,4],[9,1])),7.5)
if __name__ == '__main__':
unittest.main()