Files
python_test/hanoi/unittest_hanoi.py
T

66 lines
2.4 KiB
Python

import unittest
import io
import sys
from hanoi import tower_of_hanoi, prompt_for_integer
class TestTowerOfHanoi(unittest.TestCase):
"""
Explanation of Tests:
test_valid_input():
This test checks the core functionality by moving 3 disks using tower_of_hanoi.
It asserts that the function completes without raising errors.
test_edge_case_single_disk():
This handles the base case of a single disk, ensuring the correct move
is printed ("Move disk 1 from A to C").
test_invalid_input_zero_disks():
This checks that the function raises a ValueError when given zero disks.
test_prompt_for_integer_valid():
Tests the input function with valid integer input ("3") and asserts it
returns the correct value (3).
test_prompt_for_integer_invalid_negative():
Checks for handling negative integers, expecting a ValueError.
test_prompt_for_integer_invalid_string():
Tests that invalid string input is handled gracefully and eventually
leads to a valid integer being returned.
"""
def test_valid_input(self):
self.assertEqual(tower_of_hanoi(3, 'A', 'B', 'C'), None) # Example with 3 disks
def test_edge_case_single_disk(self):
expected_output = "Move disk 1 from A to C\n"
captured_output = io.StringIO()
sys.stdout = captured_output
tower_of_hanoi(1, 'A', 'B', 'C')
sys.stdout = sys.__stdout__ # Reset stdout
self.assertEqual(captured_output.getvalue(), expected_output)
def test_invalid_input_zero_disks(self):
with self.assertRaises(ValueError):
tower_of_hanoi(0, 'A', 'B', 'C')
def test_prompt_for_integer_valid(self):
with io.StringIO("3\n") as mock_stdin:
sys.stdin = mock_stdin
self.assertEqual(prompt_for_integer(), 3)
def test_prompt_for_integer_invalid_negative(self):
with io.StringIO("-2\n1\n") as mock_stdin:
sys.stdin = mock_stdin
self.assertEqual(prompt_for_integer(), 1) # Should eventually get a valid integer
def test_prompt_for_integer_invalid_string(self):
with io.StringIO("abc\n3\n") as mock_stdin:
sys.stdin = mock_stdin
self.assertEqual(prompt_for_integer(), 3) # Should eventually get a valid integer
if __name__ == '__main__':
unittest.main()