예제 #1
0
 def load_from_ribs_list(graph: Graph, file_name: str):
     graph.clear()
     with open(file_name, mode='r') as file:
         for line in file:
             name = ''
             params = []
             for index in line:
                 if index == '{':
                     value = ''
                 if index.isdigit():
                     value += index
                 if index == '(':
                     name = value
                     value = ''
                 if index == ',':
                     params.append(value)
                     value = ''
                 if index == ')':
                     params.append(value)
                     print(params, name)
                     value = ''
                     graph.add_vertex(params[1], random.randint(0, 100),
                                      random.randint(0, 100))
                     graph.add_vertex(params[2], random.randint(0, 100),
                                      random.randint(0, 100))
                     graph.add_edge(params[2], params[1], int(params[0]))
                     graph.oriented = bool(int(params[3]))
                     params = []
예제 #2
0
 def test_add_vertex(self):
     graph = Graph(directed=True)
     graph.add_vertex(data='a')
     self.assertEqual(set(list(graph.adjacency_list.keys())), set(['a']))
     graph.add_vertex(data=123)
     self.assertEqual(
         set(list(graph.adjacency_list.keys())), set([123, 'a']))
예제 #3
0
 def test_add_edge(self):
     graph = Graph(directed=True)
     graph.add_vertex(data='a')
     graph.add_vertex(data=123)
     graph.add_edge(data1='a', data2=123, weight=3)
     self.assertEqual(graph.adjacency_list['a'].adjacent[123], 3)
     self.assertEqual(graph.adjacency_list[123].adjacent, {})
def test_graph():
    graph = Graph()

    graph.add_vertex('A')
    graph.add_vertex('B')
    graph.add_vertex('C')
    graph.add_vertex('D')

    graph.add_edge('A', 'B', 1)
    graph.add_edge('B', 'C', 2)
    graph.add_edge('C', 'D', 3)
    graph.add_edge('A', 'C', 4)
    graph.add_edge('B', 'D', 5)
    graph.add_edge('A', 'D', 6)

    actual1 = graph.size()
    expected1 = 4

    actual2 = graph.get_vertices()
    expected2 = ['A', 'B', 'C', 'D']

    actual3 = graph.get_neighbors('A')
    expected3 = [['B', 1], ['C', 4], ['D', 6]]

    assert actual1 == expected1
    assert actual2 == expected2
    assert actual3 == expected3
def test_get_neighbors():
    graph = Graph()
    babies = graph.add_vertex('babies')
    goats = graph.add_vertex('goats')
    graph.add_edge(babies, goats, 10)
    neighbors = graph.get_neighbors(babies)
    assert goats in neighbors
def test_can_add_edge():
    graph = Graph()
    babies = graph.add_vertex('babies')
    goats = graph.add_vertex('goats')
    graph.add_edge(babies, goats, 10)
    assert goats in graph._adjacency_list[babies]
    assert graph._adjacency_list[babies][goats] == 10
def test_get_vertices():
    graph = Graph()
    vertex1 = graph.add_vertex('meat')
    vertex2 = graph.add_vertex('cheese')
    graph.add_edge(vertex1, vertex2, 11)
    output = graph.get_vertices()
    assert output == ['meat', 'cheese']
예제 #8
0
def test_add_edge_missing_vertex():
    g = Graph()
    h = Graph()
    apple = g.add_vertex('apple')
    banana = h.add_vertex('banana')
    g.add_edge(apple, banana, 4)
    for v in g.get_vertices():
        if v.value == 'apple':
            assert v.adjacencies == []
예제 #9
0
def test_get_neighbors():
    g = Graph()
    apple = g.add_vertex('apple')
    banana = g.add_vertex('banana')
    cucumber = g.add_vertex('cucumber')
    g.add_edge(apple, banana, 4)
    g.add_edge(apple, cucumber, 5)
    neighbors = g.get_neighbors(apple)
    assert neighbors == [(banana, 4), (cucumber, 5)]
예제 #10
0
    def test_add_vertex(self):
        g = Graph()
        g.add_vertex('v1')
        self.assertEqual(1, len(g.vertices))
        self.assertRaises(ValueError, g.add_vertex, 'v1')

        vertex = Vertex('v2')
        g.add_vertex(vertex)
        self.assertEqual(2, len(g.vertices))
        self.assertRaises(ValueError, g.add_vertex, vertex)
예제 #11
0
def test_add_weightless_edge():
    g = Graph()
    apple = g.add_vertex('apple')
    banana = g.add_vertex('banana')
    g.add_edge(apple, banana)
    for v in g.get_vertices():
        if v.value == 'apple':
            assert (banana, 0) in v.adjacencies
        if v.value == 'banana':
            assert (apple, 0) in v.adjacencies
예제 #12
0
def earliest_ancestor(relation, starting_child):

    graph = Graph()
    for parent, child in relation:
        graph.add_vertex(parent)
        graph.add_vertex(child)

    for parent, child in relation:
        graph.add_edge(child, parent)

    #print(list(graph.vertices[3]))
    return (graph.dft(starting_child))
예제 #13
0
 def generate_map(self):
     graph = Graph(list())
     coloring = 0
     while coloring < self.color_count:
         country = self.generate_country()
         count_of_neighbor = 0
         for vertex in graph.vertices:
             if vertex.is_contiguous_vertex(country) or \
                     country.is_contiguous_vertex(vertex):
                 count_of_neighbor += 1
         if count_of_neighbor == len(graph.vertices):
             graph.add_vertex(country)
             coloring += 1
     return graph
예제 #14
0
    def test_remove_vertex(self):
        g = Graph()
        vertex1 = g.add_vertex('v1')
        vertex2 = g.add_vertex('v2')
        g.add_vertex('v3')
        edge1 = g.add_edge('v1', 'v2')
        edge2 = g.add_edge('v1', 'v3')
        edge3 = g.add_edge('v2', 'v3')

        g.remove_vertex('v3')
        self.assertEqual(2, len(g.vertices))
        self.assertEqual(1, len(g.edges))
        self.assertTrue('v3' not in g.vertices)
        self.assertEqual(1, len(vertex1.neighbors))
        self.assertEqual(1, len(vertex2.neighbors))
예제 #15
0
    def test_get_successor_predecessor(self):
        g = Graph()
        v1 = g.add_vertex('v1')
        v2 = g.add_vertex('v2')
        v3 = g.add_vertex('v3')
        e1 = g.add_edge(v1, v2)
        e2 = g.add_edge(v1, v3)
        e3 = g.add_edge(v2, v3)

        self.assertEqual(2, len(v1.get_successors()))
        self.assertEqual(1, len(v2.get_successors()))
        self.assertEqual(0, len(v3.get_successors()))

        self.assertEqual(0, len(v1.get_predecessors()))
        self.assertEqual(1, len(v2.get_predecessors()))
        self.assertEqual(2, len(v3.get_predecessors()))
예제 #16
0
    def test_get_vertex(self):
        g = Graph()
        vertex = g.add_vertex('v1')

        self.assertEqual(vertex, g.get_vertex('v1'))
        self.assertEqual(vertex, g.get_vertex(vertex))
        self.assertRaises(ValueError, g.get_vertex, 'v2')
예제 #17
0
    def test_add_edge(self):
        g = Graph()
        g.add_vertex('v1')
        g.add_vertex('v2')
        g.add_vertex('v3')
        g.add_vertex('v4')

        edge = g.add_edge('v1', 'v2')
        self.assertEqual(1, len(g.edges))
        self.assertEqual(1, len(g.get_vertex('v1').neighbors))
        self.assertEqual(1, len(g.get_vertex('v2').neighbors))
        self.assertTrue(g.get_vertex('v1') in edge.get_vertices())
        self.assertTrue(g.get_vertex('v2') in edge.get_vertices())

        edge = g.add_edge('v3', 'v4', label='foo', value=10)
        self.assertEqual('foo', edge.label)
        self.assertEqual(10, edge.value)
예제 #18
0
def test_add_two_vertices():
    g = Graph()
    v1 = g.add_vertex('A')
    v2 = g.add_vertex('B')
    assert v1.value == 'A'
    assert v1 in g.get_vertices()
    assert v2.value == 'B'
    assert v2 in g.get_vertices()
예제 #19
0
def test_islands_depth_first_traverse():
    graph = Graph()
    a = graph.add_vertex('A')
    b = graph.add_vertex('B')
    c = graph.add_vertex('C')
    d = graph.add_vertex('D')
    e = graph.add_vertex('E')
    f = graph.add_vertex('F')
    g = graph.add_vertex('G')
    h = graph.add_vertex('H')
    graph.add_edge(a, d)
    graph.add_edge(c, g)
    graph.add_edge(d, e)
    graph.add_edge(d, h)
    graph.add_edge(d, f)
    graph.add_edge(f, h)
    assert graph.depth_first_traverse(a) == ['A', 'D', 'E', 'H', 'F']
예제 #20
0
def test_breadth_first_traverse_different_origins():
    g = Graph()
    a = g.add_vertex('A')
    b = g.add_vertex('B')
    c = g.add_vertex('C')
    d = g.add_vertex('D')
    e = g.add_vertex('E')
    f = g.add_vertex('F')
    g.add_edge(a, b)
    g.add_edge(b, c)
    g.add_edge(b, d)
    g.add_edge(c, e)
    g.add_edge(d, f)
    g.add_edge(e, f)
    assert g.breadth_first_traverse(a) == ['A', 'B', 'C', 'D', 'E', 'F']
    assert g.breadth_first_traverse(f) == ['F', 'D', 'E', 'B', 'C', 'A']
    assert g.breadth_first_traverse(c) == ['C', 'B', 'E', 'A', 'D', 'F']
예제 #21
0
    def test_remove_edge(self):
        g = Graph()
        vertex1 = g.add_vertex('v1')
        vertex2 = g.add_vertex('v2')
        vertex3 = g.add_vertex('v3')
        edge1 = g.add_edge(vertex1, vertex2)
        edge2 = g.add_edge(vertex2, vertex3)

        g.remove_edge(edge1)
        self.assertEqual(1, len(g.edges))
        self.assertTrue(edge1 not in g.edges)
        self.assertTrue(vertex2 not in vertex1.neighbors)

        g.remove_edge_between('v2', vertex3)
        self.assertEqual(0, len(g.edges))
        self.assertTrue(edge2 not in g.edges)
        self.assertTrue(vertex3 not in vertex2.neighbors)
예제 #22
0
 def load_from_adjacency_matrix(graph: Graph, file_name: str):
     matrix1 = []
     with open(file_name, mode='r') as file:
         for line in file:
             data = []
             for weights in line:
                 if LoadGraph.__isfloat(weights):
                     data.append(weights)
             matrix1.append(data)
         matrix1 = [x for x in matrix1 if x != []]
         for i in range(len(matrix1)):
             for j in range(len(matrix1[i])):
                 if matrix1[i][j] != '0' and i != []:
                     graph.add_vertex(str(i + 1), random.randint(-50, 100),
                                      random.randint(0, 100))
                     graph.add_vertex(str(j + 1), random.randint(-50, 100),
                                      random.randint(0, 100))
                     graph.add_edge(str(i + 1), str(j + 1),
                                    int(matrix1[i][j]))
예제 #23
0
def test_path_exists():
    g = Graph()
    a = g.add_vertex('A')
    b = g.add_vertex('B')
    c = g.add_vertex('C')
    d = g.add_vertex('D')
    e = g.add_vertex('E')
    f = g.add_vertex('F')
    g.add_edge(a, b)
    g.add_edge(b, c)
    g.add_edge(c, a)
    g.add_edge(d, e)
    g.add_edge(e, f)
    g.add_edge(f, d)
    assert g.does_path_exist(a, b)
    assert g.does_path_exist(a, c)
    assert g.does_path_exist(d, e)
    assert not g.does_path_exist(a, e)
    assert not g.does_path_exist(f, c)
예제 #24
0
 def load_from_arc_list(graph: Graph, file_name: str):
     graph.clear()
     with open(file_name, mode='r') as file:
         for line in file:
             name = ''
             x = ''
             for index in line:
                 if index == '{':
                     value = ''
                 if index.isdigit() or index == '.' or index == '-':
                     value += index
                 if index == ',':
                     x = value
                     value = ''
                 if index == '(':
                     name = value
                     value = ''
                 if index == ')':
                     graph.add_vertex(name, float(x), float(value))
                     value = ''
예제 #25
0
 def load_from_incidence_matrix(graph: Graph, file_name: str):
     matrix = []
     with open(file_name, mode='r') as file:
         data = file.read()
         data = data.replace('.', ',')
         data = data.replace(',]', ']')
         data = data.replace('\n', ',')
         matrix = json.loads(data)
         for line in matrix:
             for i in range(len(line)):
                 if line[i] < 0:
                     v_from = i + 1
                     break
             for i in range(len(line)):
                 if line[i] > 0:
                     v_to = i + 1
                     break
             graph.add_vertex(str(v_from))
             graph.add_vertex(str(v_to))
             graph.add_edge(str(v_from), str(v_to), v_to)
예제 #26
0
def earliest_ancestor(ancestors, starting_node):
    graph = Graph()
    for vertex_1, vertex_2 in ancestors:
        graph.add_vertex(vertex_1)
        graph.add_vertex(vertex_2)
        # add edges
    for vertex_1, vertex_2 in ancestors:
        graph.add_edge(vertex_1, vertex_2)

    targetVertex = None
    longestPath = 1
    for vertex in graph.vertices:
        path = graph.dfs(vertex, starting_node)
        if path:
            if len(path) > longestPath:
                longestPath = len(path)
                targetVertex = vertex
        elif not path and longestPath == 1:
            targetVertex = -1

    return targetVertex
def test_breadth_first_traversal():
    graph = Graph()

    pandora = graph.add_vertex('Pandora')
    arendelle = graph.add_vertex('Arendelle')
    metroville = graph.add_vertex('Metroville')
    monstroplolis = graph.add_vertex('Monstroplolis')
    narnia = graph.add_vertex('Narnia')
    naboo = graph.add_vertex('Naboo')

    graph.add_edge(pandora, arendelle)
    graph.add_edge(arendelle, metroville)
    graph.add_edge(arendelle, monstroplolis)
    graph.add_edge(monstroplolis, metroville)
    graph.add_edge(metroville, narnia)
    graph.add_edge(metroville, naboo)
    graph.add_edge(monstroplolis, naboo)
    graph.add_edge(naboo, narnia)

    babies = graph.traverse(pandora)

    assert babies == [
        'Pandora', 'Arendelle', 'Metroville', 'Monstroplolis', 'Naboo',
        'Narnia'
    ]
예제 #28
0
def generate(size: int = 10000, edge_count: int = 4) -> Graph:
    size = int(np.sqrt(size)**2)
    vertexes = np.arange(1, size + 1).reshape(
        (int(np.sqrt(size)), int(np.sqrt(size)))).tolist()

    graph = Graph()
    graph.oriented = False

    for i in range(len(vertexes)):
        for j in range(len(vertexes)):
            x = (VERTEX_RADIUS * j + SPACE * (j - 1))
            y = (VERTEX_RADIUS * i + SPACE * (i - 1))
            graph.add_vertex(str(vertexes[i][j]), x, y, shadowed=True)

    for i in range(len(vertexes)):
        for j in range(len(vertexes)):
            neighbor = neighbor_keys.copy()
            for k in range(edge_count):
                move = None
                while move is None:
                    choice = random.choice(neighbor)
                    move = neighbor_dict[choice]
                    neighbor.pop(neighbor.index(choice))
                    if i + move[0] < 0 or j + move[1] < 0:
                        move = None
                        continue
                    try:
                        vertexes[i + move[0]][j + move[1]]
                    except IndexError:
                        move = None

                v1 = graph.vertexes_coordinates[str(vertexes[i][j])]
                v2 = graph.vertexes_coordinates[str(
                    vertexes[i + move[0]][j + move[1]])]
                dist = int(np.sqrt((v2.x - v1.x)**2 + (v2.y - v1.y)**2))

                graph.add_edge(v1.name, v2.name, dist, shadowed=True)

    return graph
예제 #29
0
def test_depth_first_traverse_with_diff_root():
    graph = Graph()
    a = graph.add_vertex('A')
    b = graph.add_vertex('B')
    c = graph.add_vertex('C')
    d = graph.add_vertex('D')
    e = graph.add_vertex('E')
    f = graph.add_vertex('F')
    g = graph.add_vertex('G')
    h = graph.add_vertex('H')
    graph.add_edge(a, b)
    graph.add_edge(a, d)
    graph.add_edge(b, c)
    graph.add_edge(c, g)
    graph.add_edge(d, f)
    graph.add_edge(d, e)
    graph.add_edge(d, h)
    graph.add_edge(f, h)
    assert graph.depth_first_traverse(e) == [
        'E', 'D', 'A', 'B', 'C', 'G', 'F', 'H'
    ]
    assert graph.depth_first_traverse(d) == [
        'D', 'A', 'B', 'C', 'G', 'F', 'H', 'E'
    ]
 def lets_test_this_breakpoint_thing(debug=False):
     graph = Graph()
     farm_animals = [
         'goats', 'chickens', 'cows', 'pigs', 'more cows', 'zebra', 'lions',
         'more pigs', 'spiders', 'more goats', 'more chickens'
     ]
     barnyard = [graph.add_vertex(animal) for animal in farm_animals]
     [
         graph.add_edge(animal1, animal2, 'double food for you guys')
         for animal1 in barnyard for animal2 in barnyard
         if animal1.value in animal2.value[1:]
     ]
     for animal1 in barnyard:
         for animal2 in barnyard:
             if animal1.value in animal2.value[1:]:
                 assert graph._adjacency_list[animal1][
                     animal2] == 'double food for you guys'
                 if debug:
                     breakpoint()
예제 #31
0
def test_breadth_first_traverse_with_islands():
    g = Graph()
    pan = g.add_vertex('Pandora')
    are = g.add_vertex('Arendelle')
    met = g.add_vertex('Metroville')
    mon = g.add_vertex('Monstropolis')
    nab = g.add_vertex('Naboo')
    nar = g.add_vertex('Narnia')
    g.add_edge(pan, are)
    g.add_edge(are, met)
    g.add_edge(are, mon)
    g.add_edge(met, mon)
    g.add_edge(nar, nab)
    places = g.breadth_first_traverse(pan)
    assert places == ['Pandora', 'Arendelle', 'Metroville', 'Monstropolis']
def test_city_path_finder():
    def business_trip(graph, arr_cities):
        if not graph._adjacency_list:
            return False, 0

        cost = 0
        for i, city in enumerate(arr_cities):
            neighbors = graph.get_neighbors(city)
            if i + 1 >= len(arr_cities):  # if we're at the end of the list
                return True, cost
            if arr_cities[i + 1] in neighbors:
                cost += neighbors.get(arr_cities[i + 1])
                continue
            return False, 0

    graph = Graph('bidirectional')

    pandora = graph.add_vertex('Pandora')
    arendelle = graph.add_vertex('Arendelle')
    metroville = graph.add_vertex('Metroville')
    monstroplolis = graph.add_vertex('Monstroplolis')
    narnia = graph.add_vertex('Narnia')
    naboo = graph.add_vertex('Naboo')

    cities1 = [metroville, pandora]
    cities2 = [arendelle, monstroplolis, naboo]
    cities3 = [naboo, pandora]
    cities4 = [narnia, arendelle, naboo]
    test_cases = [cities1, cities2, cities3, cities4]
    expected_results = [(True, 82), (True, 115), (False, 0), (False, 0)]

    graph.add_edge(pandora, arendelle, 150)
    graph.add_edge(pandora, metroville, 82)
    graph.add_edge(arendelle, metroville, 99)
    graph.add_edge(arendelle, monstroplolis, 42)
    graph.add_edge(metroville, monstroplolis, 105)
    graph.add_edge(metroville, narnia, 37)
    graph.add_edge(metroville, naboo, 26)
    graph.add_edge(naboo, narnia, 250)
    graph.add_edge(monstroplolis, naboo, 73)

    for i, test in enumerate(test_cases):
        assert business_trip(graph, test) == expected_results[i]
def test_breadth_first():
    graph2 = Graph()

    graph2.add_vertex('E')
    graph2.add_vertex('F')
    graph2.add_vertex('G')
    graph2.add_vertex('H')
    graph2.add_vertex('I')
    graph2.add_vertex('J')

    graph2.add_edge('E', 'F', 7)
    graph2.add_edge('E', 'G', 8)
    graph2.add_edge('G', 'H', 9)
    graph2.add_edge('G', 'I', 10)
    graph2.add_edge('H', 'J', 11)
    graph2.add_edge('I', 'J', 12)

    actual = graph2.breadth_first('E')

    expected = ['E', 'F', 'G', 'H', 'I', 'J']

    assert actual == expected
예제 #34
0
class TestGraphQuery(unittest.TestCase):
	""" Tests for graph queries.

	Tests for graph queries.
	Tests include testsing longest edge, shortest edge, average edge distance, biggest vertex,
	smallest vertex, average vertex size, continents info, hub cities, and map url.

	"""
	def setUp(self):
		self.graph = Graph()
		self.graph.load("../json/test_data.json")


	def test_longest_edge(self):
		longest_edge = sorted(self.graph.calculate_longest_edge(), key=lambda x: x.departure.code)
		self.assertEqual(longest_edge[0].departure.code, "LIM")
		self.assertEqual(longest_edge[1].departure.code, "MEX")
		self.assertEqual(longest_edge[0].distance, 24530)


	def test_shortest_edge(self):
		shortest_edge = sorted(self.graph.calculate_shortest_edge(), key=lambda x: x.departure.code)
		self.assertEqual(shortest_edge[1].departure.code, "SCL")
		self.assertEqual(shortest_edge[0].departure.code, "LIM")
		self.assertEqual(shortest_edge[0].distance, 2453)


	def test_average_distance(self):
		average_distance = self. graph.calculate_average_distance()
		self.assertEqual(int(average_distance), 10594)


	def test_biggest_vertex(self):
		biggest_vertex = self.graph.calculate_biggest_vertex()
		self.assertEqual(biggest_vertex.code, "MEX")


	def test_smallest_vertex(self):
		smallest_vertex =self.graph.calculate_smallest_vertex()
		self.assertEqual(smallest_vertex.code, "SCL")


	def test_average_size(self):
		average_size = self. graph.calculate_average_vertex_size()
		self.assertEqual(int(average_size), 12816666)


	def test_continents_info(self):
		continents_dict = self.graph.calculate_continents_info()
		self.assertTrue("South America" in continents_dict.keys())
		self.assertTrue("North America" in continents_dict.keys())
		cities = []
		for value in continents_dict.values():
			for city in value:
				cities.append(city.code)
		self.assertTrue("MEX" in cities)
		self.assertTrue("SCL" in cities)
		self.assertTrue("LIM" in cities)


	def test_hub_cities(self):
		hub_cities = self.graph.calculate_hub_cities()
		hub_cities = [hub_cities[0].code, hub_cities[1].code, hub_cities[2].code]
		self.assertTrue("MEX" in hub_cities)
		self.assertTrue("SCL" in hub_cities)
		self.assertTrue("MEX" in hub_cities)


	def test_map_url(self):
		url = self.graph.generate_map_url()
		self.assertTrue("MEX-SCL" in url)
		self.assertTrue("LIM-MEX" in url)
		self.assertTrue("SCL-LIM" in url)


	def test_add_vertex(self):
		self.assertTrue(self.graph.add_vertex(city))
		self.assertTrue("CMI" in self.graph.vertices.keys())
		self.assertEqual(self.graph.vertices["CMI"].name, "Champaign")


	def test_add_edge(self):
		self.assertTrue(self.graph.add_vertex(city))
		self.assertFalse(self.graph.add_edge("CMI", "PAR", 30000))
		self.assertTrue(self.graph.add_edge("CMI", "MEX", 30000))
		edges = []
		for edge in self.graph.edges.values():
			edges.append(edge.departure.code + " -> " + edge.destination.code + ", " + str(edge.distance))
		edges.sort()
		self.assertEqual(edges, ['CMI -> MEX, 30000', 'LIM -> MEX, 24530', 'LIM -> SCL, 2453', 'MEX -> LIM, 24530', 'MEX -> SCL, 4800', 'SCL -> LIM, 2453', 'SCL -> MEX, 4800'])


	def test_remove_edge(self):
		self.assertFalse(self.graph.remove_edge("CMI", "PAR"))
		self.assertTrue(self.graph.add_vertex(city))
		self.assertTrue(self.graph.add_edge("CMI", "MEX", 30000))
		self.assertTrue(self.graph.remove_edge("CMI", "MEX"))
		edges = []
		for edge in self.graph.edges.values():
			edges.append(edge.departure.code + " -> " + edge.destination.code + ", " + str(edge.distance))
		edges.sort()
		self.assertEqual(edges, ['LIM -> MEX, 24530', 'LIM -> SCL, 2453', 'MEX -> LIM, 24530', 'MEX -> SCL, 4800', 'SCL -> LIM, 2453', 'SCL -> MEX, 4800'])


	def test_remove_vertex(self):
		self.assertFalse(self.graph.remove_vertex("PAR"))
		self.assertTrue(self.graph.add_vertex(city))
		self.assertTrue(self.graph.add_edge("CMI", "MEX", 30000))
		self.assertTrue(self.graph.remove_vertex("CMI"))
		self.assertFalse("CMI" in self.graph.vertices.keys())
		edges = []
		for edge in self.graph.edges.values():
			edges.append(edge.departure.code + " -> " + edge.destination.code + ", " + str(edge.distance))
		edges.sort()
		self.assertEqual(edges, ['LIM -> MEX, 24530', 'LIM -> SCL, 2453', 'MEX -> LIM, 24530', 'MEX -> SCL, 4800', 'SCL -> LIM, 2453', 'SCL -> MEX, 4800'])


	def test_save_to_disk(self):
		test_string = '{"metros": [{"code": "LIM", "continent": "South America", "coordinates": {"S": 12, "W": 77}, "country": "PE", "name": "Lima", "population": 9050000, "region": 1, "timezone": -5}, {"code": "MEX", "continent": "North America", "coordinates": {"N": 19, "W": 99}, "country": "MX", "name": "Mexico City", "population": 23400000, "region": 1, "timezone": -6}, {"code": "SCL", "continent": "South America", "coordinates": {"S": 33, "W": 71}, "country": "CL", "name": "Santiago", "population": 6000000, "region": 1, "timezone": -4}], "routes": [{"distance": 24530, "ports": ["LIM", "MEX"]}, {"distance": 2453, "ports": ["LIM", "SCL"]}, {"distance": 24530, "ports": ["MEX", "LIM"]}, {"distance": 4800, "ports": ["MEX", "SCL"]}, {"distance": 2453, "ports": ["SCL", "LIM"]}, {"distance": 4800, "ports": ["SCL", "MEX"]}]}'
		json_string = json.dumps(self.graph.convert_to_json(), sort_keys=True)
		self.assertEqual(json_string, test_string)


	def test_route_info(self):
		route = ['MEX', 'SCL', 'LIM']
		self.assertTrue(self.graph.is_valid_route(route))
		cost, time = self.graph.calculate_route_info(route)
		self.assertEqual(cost, 2415.90)
		self.assertEqual(time, 12.57)
		self.graph.remove_edge("MEX", "SCL")
		self.assertFalse(self.graph.is_valid_route(route))


	def test_shortest_path(self):
		shortest_path = ['MEX', 'SCL', 'LIM']
		route = self.graph.calculate_shortest_path(['MEX', 'LIM'])
		self.assertEqual(route, shortest_path)
		self.assertTrue(self.graph.add_vertex(city))
		route = self.graph.calculate_shortest_path(['MEX', 'CMI'])
		self.assertEqual(route, None)
예제 #35
0
def test_size():
    g = Graph()
    g.add_vertex('apple')
    g.add_vertex('banana')
    g.add_vertex('cucumber')
    assert g.size() == 3
예제 #36
0
def test_get_vertices():
    g = Graph()
    apple = g.add_vertex('apple')
    banana = g.add_vertex('banana')
    vertices = g.get_vertices()
    assert vertices == {apple, banana}
예제 #37
0
def test_add_one_vertext():
    g = Graph()
    v = g.add_vertex('A')
    assert v in g.get_vertices()