Skip to content

Commit

Permalink
Merge pull request #40 from srajan-kiyotaka/sracho
Browse files Browse the repository at this point in the history
Unit Tests + Bugs
  • Loading branch information
srajan-kiyotaka authored Jun 11, 2024
2 parents b748bf8 + 9e107ca commit 8b3dd3f
Show file tree
Hide file tree
Showing 7 changed files with 688 additions and 47 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@ traverseCraft/__pycache__
test_grid.py
test_tree.py
test_graph.py
test_*.py
test_unit.py
test.py
Empty file added tests/test_graph_world.py
Empty file.
143 changes: 143 additions & 0 deletions tests/test_grid_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
import unittest
from tkinter import Tk
from unittest.mock import patch
from traverseCraft.world import CreateGridWorld
from traverseCraft.agent import GridAgent

class TestGridAgent(unittest.TestCase):
def setUp(self):
# Setup code to initialize the grid world
self.grid_world = CreateGridWorld(worldName='Test Grid', rows=10, cols=10, cellSize=20, pathColor="black", blockColor="pink", goalColor="aqua", cellPadding=4, borderWidth=2, buttonBgColor="#7FC8D9", buttonFgColor="#332942", textFont="Helvetica", textSize=20, textWeight="bold", buttonText="Test Start Agent", logoPath=None)

# Set goal state
self.grid_world.addGoalState([[5, 5], [6, 9], [8, 8]])

# Set block state
self.grid_world.addBlockPath([[1, 1], [2, 2], [3, 3], [2, 7], [8, 5], [6, 1]])

# Construct the grid world
self.grid_world.constructWorld()

# Initialize the grid agent
self.agent = GridAgent(self.grid_world, agentName='TestAgent', agentColor='blue', heatMapView=True, heatMapColor='#FFA732', agentPos=(0, 0), heatGradient=0.05)

def tearDown(self):
# Destroy the root window after each test
try:
self.grid_world._root.destroy()
except Exception as e:
print(f"Exception in tearDown: {e}")


def test_initialization(self):
# Test initialization of the grid agent
self.assertIsInstance(self.agent._worldObj, CreateGridWorld)
self.assertEqual(self.agent._agentName, 'TestAgent')
self.assertEqual(self.agent._agentColor, 'blue')
self.assertTrue(self.agent._heatMapView)
self.assertEqual(self.agent._heatMapColor, '#FFA732')
self.assertEqual(self.agent._heatGradient, 0.05)
self.assertEqual(self.agent._startState, (0, 0))
self.assertEqual(self.agent._currentPosition, (0, 0))
self.assertIsNone(self.agent.algorithmCallBack)

def test_initial_start_state(self):
# Test initial start state
self.assertEqual(self.agent._startState, (0, 0))
self.assertEqual(self.agent._currentPosition, (0, 0))


def test_set_start_state(self):
# Update start state
self.agent.setStartState(1, 8)

# Verify updated start state
self.assertEqual(self.agent._startState, (1, 8))
self.assertEqual(self.agent._currentPosition, (1, 8))
self.assertEqual(self.grid_world._cells[1][8].cget("bg"), 'blue') # Check if cell color updated
self.assertEqual(self.grid_world._cells[0][0].cget("bg"), 'black') # Check previous cell color


# Update start state again
self.agent.setStartState(3, 6)

# Verify updated start state
self.assertEqual(self.agent._startState, (3, 6))
self.assertEqual(self.agent._currentPosition, (3, 6))
self.assertEqual(self.grid_world._cells[3][6].cget("bg"), 'blue') # Check if cell color updated
self.assertEqual(self.grid_world._cells[1][8].cget("bg"), 'black') # Check previous cell color


def test_invalid_start_state(self):
# Test setting an invalid start state
with self.assertRaises(ValueError):
self.agent.setStartState(20, 20) # Invalid position, should raise ValueError

# Verify that start state remains unchanged
self.assertEqual(self.agent._startState, (0, 0))
self.assertEqual(self.agent._currentPosition, (0, 0))


def test_check_goal_state(self):

# Check goal states
self.assertTrue(self.agent.checkGoalState(5, 5)) # Should return True
self.assertTrue(self.agent.checkGoalState(6, 9)) # Should return True
self.assertTrue(self.agent.checkGoalState(8, 8)) # Should return True
self.assertFalse(self.agent.checkGoalState(0, 0)) # Should return False

def test_check_block_state(self):
# Check block states
self.assertTrue(self.agent.checkBlockState(1, 1)) # Should return True
self.assertTrue(self.agent.checkBlockState(2, 2)) # Should return True
self.assertTrue(self.agent.checkBlockState(3, 3)) # Should return True
self.assertTrue(self.agent.checkBlockState(2, 7)) # Should return True
self.assertTrue(self.agent.checkBlockState(8, 5)) # Should return True
self.assertTrue(self.agent.checkBlockState(6, 1)) # Should return True
self.assertFalse(self.agent.checkBlockState(0, 0)) # Should return False

def test_set_algorithm_callback(self):
# Define a sample callback function
def sample_callback():
pass

# Set the callback function
self.agent.setAlgorithmCallBack(sample_callback)

# Verify that the callback function is set
self.assertEqual(self.agent.algorithmCallBack, sample_callback)

def test_run_algorithm(self):
# Define a sample algorithm callback function
def sample_algorithm():
pass

# Set the algorithm callback function
self.agent.setAlgorithmCallBack(sample_algorithm)

# Run the algorithm
self.agent.runAlgorithm()

# Verify that the algorithm ran successfully (no errors raised)
self.assertTrue(True)

def test_move_agent(self):
# Define a sample algorithm callback function
def sample_algorithm():
pass

# Set the algorithm callback function
self.agent.setAlgorithmCallBack(sample_algorithm)

# Run the algorithm
self.agent.runAlgorithm()

# Move the agent
self.assertTrue(self.agent.moveAgent(1, 0)) # Should return True
self.assertEqual(self.agent._currentPosition, (1, 0)) # Verify agent's current position
self.assertTrue(self.agent.moveAgent(0, 3)) # Should return True
self.assertEqual(self.agent._currentPosition, (0, 3)) # Verify agent's current position


if __name__ == '__main__':
unittest.main()
128 changes: 128 additions & 0 deletions tests/test_grid_world.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import unittest
from tkinter import Tk
from unittest.mock import patch
from traverseCraft.world import CreateGridWorld
from traverseCraft.agent import GridAgent

class TestGridWorld(unittest.TestCase):
def setUp(self):
# Setup code to initialize the grid world
self.grid_world = CreateGridWorld(worldName='Test Grid', rows=10, cols=10, cellSize=20, pathColor="black", blockColor="pink", goalColor="aqua", cellPadding=4, borderWidth=2, buttonBgColor="#7FC8D9", buttonFgColor="#332942", textFont="Helvetica", textSize=20, textWeight="bold", buttonText="Test Start Agent", logoPath=None)


def tearDown(self):
try:
self.grid_world._root.destroy()
except Exception as e:
print(f"Exception in tearDown: {e}")

def test_initial_state(self):
# Test the initial state of the grid world
self.assertEqual(self.grid_world._worldName, 'Test Grid')
self.assertEqual(self.grid_world._rows, 10)
self.assertEqual(self.grid_world._cols, 10)
self.assertEqual(self.grid_world._cellSize, 20)
self.assertEqual(self.grid_world._pathColor, "black")
self.assertEqual(self.grid_world._blockColor, "pink")
self.assertEqual(self.grid_world._goalColor, "aqua")
self.assertEqual(self.grid_world._cellPadding, 4)
self.assertEqual(self.grid_world._borderWidth, 2)
self.assertEqual(self.grid_world._buttonBgColor, "#7FC8D9")
self.assertEqual(self.grid_world._buttonFgColor, "#332942")
self.assertEqual(self.grid_world._textFont, "Helvetica")
self.assertEqual(self.grid_world._textSize, 20)
self.assertEqual(self.grid_world._textWeight, "bold")
self.assertEqual(self.grid_world._buttonText, "Test Start Agent")
self.assertIsNone(self.grid_world._agent)

def test_heat_map_initialization(self):
# Check if the heat map grid is initialized correctly
expected_rows = 10
expected_cols = 10

self.assertEqual(len(self.grid_world._heatMapValueGrid), expected_rows, "Number of rows in heat map grid is incorrect.")
for row in self.grid_world._heatMapValueGrid:
self.assertEqual(len(row), expected_cols, "Number of columns in heat map grid is incorrect.")
self.assertTrue(all(value == 0 for value in row), "Initial heat map values should be 0.")

def test_cells_not_none_and_bound(self):
# Define the block path to be added
block_path = [[1, 1], [2, 2], [3, 3], [2, 7], [8, 5], [6, 1]]

# Add the block path to the grid world
self.grid_world.addBlockPath(block_path)

# Define the goal state to be added
goal_state = [[5, 5], [6, 9], [8, 8]]

# Add the goal state to the grid world
self.grid_world.addGoalState(goal_state)

# Construct the grid world
self.grid_world.constructWorld()

for i in range(self.grid_world._rows):
for j in range(self.grid_world._cols):
with self.subTest(i=i, j=j):
cell = self.grid_world._cells[i][j]
self.assertIsNotNone(cell, f"Cell ({i}, {j}) is None.")

# Check if the cell is a goal cell
if [i, j] in self.grid_world._goalCells:
bindings = cell.bind()
self.assertNotIn("<Button-1>", bindings, f"Goal cell ({i}, {j}) should not have <Button-1> event bound.")
else:
bindings = cell.bind()
self.assertIn("<Button-1>", bindings, f"Cell ({i}, {j}) does not have <Button-1> event bound.")

def test_add_block_path(self):
# Define the block path to be added
block_path = [[1, 1], [2, 2], [3, 3], [2, 7], [8, 5], [6, 1]]

# Add the block path to the grid world
self.grid_world.addBlockPath(block_path)

# Verify that the cells corresponding to the block path are set correctly
for coordinate in block_path:
i, j = coordinate
with self.subTest(i=i, j=j):
cell = self.grid_world._cells[i][j]
self.assertEqual(cell.cget("bg"), self.grid_world._blockColor, f"Cell ({i}, {j}) does not have block color.")
self.assertEqual(self.grid_world._world[i][j], -1, f"Cell ({i}, {j}) is not marked as a block in the world grid.")

# Check if the coordinate is present in _blockCells
self.assertIn(coordinate, self.grid_world._blockCells, f"Coordinate {coordinate} is not present in _blockCells.")

def test_add_goal_state(self):
# Define the goal state to be added
goal_state = [[5, 5], [6, 9], [8, 8]]

# Add the goal state to the grid world
self.grid_world.addGoalState(goal_state)

# Verify that the cells corresponding to the goal state are set correctly
for coordinate in goal_state:
i, j = coordinate
with self.subTest(i=i, j=j):
cell = self.grid_world._cells[i][j]
self.assertEqual(cell.cget("bg"), self.grid_world._goalColor, f"Cell ({i}, {j}) does not have goal color.")
self.assertEqual(self.grid_world._world[i][j], 1, f"Cell ({i}, {j}) is not marked as a goal state in the world grid.")

# Check if the coordinate is present in _goalCells
self.assertIn(coordinate, self.grid_world._goalCells, f"Coordinate {coordinate} is not present in _goalCells.")


@patch.object(Tk, 'mainloop', lambda self: None)
def test_show_world(self):
# Call the showWorld function
self.grid_world.showWorld()

# Verify that the _root window is initialized after calling showWorld
self.assertIsInstance(self.grid_world._root, Tk)

# Verify that the _root window is visible
self.assertTrue(self.grid_world._root.winfo_exists())


if __name__ == '__main__':
unittest.main()
113 changes: 113 additions & 0 deletions tests/test_tree_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import unittest
from tkinter import Tk
from unittest.mock import patch
from traverseCraft.world import CreateTreeWorld
from traverseCraft.agent import TreeAgent
from traverseCraft.dataStructures import TreeNode

import unittest
import time
from traverseCraft.world import CreateTreeWorld
from traverseCraft.agent import TreeAgent

class TestTreeAgent(unittest.TestCase):
def setUp(self):
# Sample tree world information
treeWorldInfo = {
'adj': {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['H'],
'F': ['G'],
'G': [],
'H': []
},
'position': {
'A': (300, 100),
'B': (150, 200),
'C': (450, 200),
'D': (100, 300),
'E': (200, 300),
'F': (300, 300),
'G': (400, 400),
'H': (150, 400)
},
'root': 'A',
'goals': ['G']
}
# Create the tree world
self.treeWorld = CreateTreeWorld("Tree World Test", treeWorldInfo)
# Construct the world
self.treeWorld.constructWorld()
# Initialize the tree agent
self.agent = TreeAgent(agentName="Test Tree Agent", world=self.treeWorld, heatMapColor="#EF4040")
# Link the agent with the world
self.treeWorld.setAgent(self.agent)

def tearDown(self):
# Destroy the root window after each test
try:
self.treeWorld._root.destroy()
self.agent = None
except Exception as e:
print(f"Exception in tearDown: {e}")

def test_initialization(self):
# Test initialization of the tree agent
self.assertIsInstance(self.agent._worldObj, CreateTreeWorld)
self.assertEqual(self.agent._agentName, "Test Tree Agent")
self.assertEqual(self.agent._agentColor, "blue") # Default value
self.assertTrue(self.agent._heatMapView) # Default value
self.assertEqual(self.agent._heatMapColor, "#EF4040")
self.assertEqual(self.agent._heatGradient, 0.05) # Default value
self.assertIsNone(self.agent.algorithmCallBack)
self.assertIsNotNone(self.agent._currentNode)

def test_set_algorithm_callback(self):
# Define a sample callback function
def sample_callback():
pass

# Set the callback function
self.agent.setAlgorithmCallBack(sample_callback)

# Verify that the callback function is set
self.assertEqual(self.agent.algorithmCallBack, sample_callback)

def test_run_algorithm(self):
# Define a sample algorithm callback function
def sample_algorithm():
pass

# Set the algorithm callback function
self.agent.setAlgorithmCallBack(sample_algorithm)

# Run the algorithm
self.agent.runAlgorithm()

# Verify that the algorithm ran successfully (no errors raised)
self.assertTrue(True)

def test_check_goal_state(self):
# Check goal state
self.assertFalse(self.agent.checkGoalState(self.agent._treeRoot)) # The root node should be a goal state
self.assertTrue(self.agent.checkGoalState(self.treeWorld.getNode('G'))) # The node 'G' should be a goal state

def test_move_agent(self):
# Get pointers to nodes 'B', 'D', and 'E' using self.treeWorld.getNode()
node_B = self.treeWorld.getNode('B')
node_C = self.treeWorld.getNode('C')
node_D = self.treeWorld.getNode('D')
node_E = self.treeWorld.getNode('E')

# Move the agent
self.assertFalse(self.agent.moveAgent(None)) # Move to None should fail
self.assertTrue(self.agent.moveAgent(node_B)) # Move to node 'B' should succeed
self.assertTrue(self.agent.moveAgent(node_C)) # Move to node 'C' should succeed
self.assertTrue(self.agent.moveAgent(node_D)) # Move to node 'D' should succeed
self.assertTrue(self.agent.moveAgent(node_E)) # Move to node 'E' should succeed

if __name__ == '__main__':
unittest.main()
Loading

0 comments on commit 8b3dd3f

Please sign in to comment.