# Calculating Euclidean distance and performing unit-testing

The method creates a link, an edge between two nodes, and calculates the Euclidean distance.

I'm testing that after linking, the link does indeed exist, and that the distance is correct.

I've used a variety of test cases, to check that it works for both horizontal and vertical links (just incase there's a divide by zero error), and as well as forward and backwards to check that it doesn't return a negative value.

import unittest
from graph import SpatialGraph

class TestSpatialGraph(unittest.TestCase):
#cleardown any existing graph.
def setUp(self):
print "TestSpatialGraph Setup"

g = None

g = SpatialGraph(2,2)

self.assertEquals(g.distMatrix[0][1],1000)
self.assertEquals(g.distMatrix[1][0],1000)

g = SpatialGraph(2,2)

self.assertEquals(g.distMatrix[0][1],1414)
self.assertEquals(g.distMatrix[1][0],1414)

g = SpatialGraph(2,2)

self.assertEquals(g.distMatrix[0][1],1000)
self.assertEquals(g.distMatrix[1][0],1000)

g = SpatialGraph(2,2)

self.assertEquals(g.distMatrix[0][1],1000)
self.assertEquals(g.distMatrix[1][0],1000)

g = SpatialGraph(2,2)

self.assertEquals(g.distMatrix[0][1],1414)
self.assertEquals(g.distMatrix[1][0],1414)

g = SpatialGraph(2,2)

self.assertEquals(g.distMatrix[0][1],1000)
self.assertEquals(g.distMatrix[1][0],1000)


Here's some questions I have:

1. Obviously the code is repetitive. But I'm told that for unit tests, you shouldn't genericise, and instead should repeat yourself. (But what if I change one of the methods use? Won't going through each of the tests and refactoring be a pain?).

2. It assumes that addNode is working correctly. But is this how unit tests work? I then also have tests to check that addNode is working correctly, and then assume after that that everywhere else it is indeed working correctly.

3. I'm not testing for more distances. This was perhaps laziness on my part. I check just the one diagonal, and it's indeed calculating that distance correctly.

4. What else am I meant to have in a setUp method?

5. Each test is in its own method. Should they perhaps be all just one test?

Since the tests are testing the same thing (calculate the distance between two nodes) and the only difference is the test data, I say refactor it so that you have one test that tests the same logic with different data. When you have tests that are there for different purposes (like validation checking, distance calculation, not calling createLink, etc) you will have code duplication.
There should be separate tests for addNode and separate tests for validation checks (what happens when you try to create a link when there are no nodes added). Also there should be different variations of the amount of nodes.
Setup is called before every testmethod, so if you always create the same SpatialGraph you can do that there.