1+ import unittest
2+ from data_classes import Graph
3+ from a_star import a_star
4+ import sys
5+ import os
6+ sys .path .insert (0 , os .path .abspath (os .path .join (os .path .dirname (__file__ ), '..' )))
7+ class TestAStar (unittest .TestCase ):
8+ def setUp (self ):
9+ vertices = {(0 , 0 ), (1 , 0 ), (1 , 1 ), (2 , 1 ), (2 , 2 )}
10+ edges = {
11+ (0 , 0 ): {(1 , 0 ): 1 },
12+ (1 , 0 ): {(1 , 1 ): 1 , (0 , 0 ): 1 },
13+ (1 , 1 ): {(2 , 1 ): 1 , (1 , 0 ): 1 },
14+ (2 , 1 ): {(2 , 2 ): 1 , (1 , 1 ): 1 },
15+ (2 , 2 ): {(2 , 1 ): 1 }
16+ }
17+ self .graph = Graph (vertices , edges )
18+ self .graph .vertices = {
19+ (0 , 0 ), (1 , 0 ), (1 , 1 ), (2 , 1 ), (2 , 2 )
20+ }
21+ self .graph .edges = {
22+ (0 , 0 ): {(1 , 0 ): 1 },
23+ (1 , 0 ): {(1 , 1 ): 1 , (0 , 0 ): 1 },
24+ (1 , 1 ): {(2 , 1 ): 1 , (1 , 0 ): 1 },
25+ (2 , 1 ): {(2 , 2 ): 1 , (1 , 1 ): 1 },
26+ (2 , 2 ): {(2 , 1 ): 1 }
27+ }
28+
29+ def test_valid_path (self ):
30+ path , cost = a_star (self .graph , (0 , 0 ), (2 , 2 ))
31+ self .assertEqual (path , [(0 , 0 ), (1 , 0 ), (1 , 1 ), (2 , 1 ), (2 , 2 )])
32+ self .assertEqual (cost , 4 )
33+
34+ def test_no_path (self ):
35+ self .graph .edges = {
36+ (0 , 0 ): {(1 , 0 ): 1 },
37+ (1 , 0 ): {(0 , 0 ): 1 },
38+ (2 , 2 ): {} # Disconnected node
39+ }
40+ with self .assertRaises (ValueError ):
41+ a_star (self .graph , (0 , 0 ), (2 , 2 ))
42+
43+ def test_same_start_end (self ):
44+ path , cost = a_star (self .graph , (1 , 1 ), (1 , 1 ))
45+ self .assertEqual (path , [(1 , 1 )])
46+ self .assertEqual (cost , 0 )
47+
48+ if __name__ == "__main__" :
49+ unittest .main ()
0 commit comments