From e8d83cd6938f4ff23abd37d2513fe9ad5acc1af4 Mon Sep 17 00:00:00 2001 From: Joakim Persson Date: Fri, 12 Jul 2024 13:19:43 +0200 Subject: [PATCH] =?UTF-8?q?F=C3=B6rsta=20version=20av=20en=20testfil=20f?= =?UTF-8?q?=C3=B6r=20projektet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hanoi/unittest_hanoi.py | 42 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 hanoi/unittest_hanoi.py diff --git a/hanoi/unittest_hanoi.py b/hanoi/unittest_hanoi.py new file mode 100644 index 0000000..7ac5685 --- /dev/null +++ b/hanoi/unittest_hanoi.py @@ -0,0 +1,42 @@ +import unittest +from hanoi import hanoi # Assuming the code is in a file named hanoi.py + +class TestHanoi(unittest.TestCase): + + def test_hanoi_with_one_disk(self): + with self.subTest(n=1, source='A', auxiliary='B', target='C'): + expected_output = "Move disk 1 from A to C\n" + with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout: + hanoi(1, 'A', 'B', 'C') + self.assertEqual(mock_stdout.getvalue(), expected_output) + + def test_hanoi_with_two_disks(self): + with self.subTest(n=2, source='A', auxiliary='B', target='C'): + expected_output = "Move disk 1 from A to B\nMove disk 2 from A to C\nMove disk 1 from B to C\n" + with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout: + hanoi(2, 'A', 'B', 'C') + self.assertEqual(mock_stdout.getvalue(), expected_output) + + def test_hanoi_with_three_disks(self): + with self.subTest(n=3, source='A', auxiliary='B', target='C'): + expected_output = "Move disk 1 from A to C\nMove disk 2 from A to B\nMove disk 1 from C to B\nMove disk 3 from A to C\nMove disk 1 from B to A\nMove disk 2 from B to C\nMove disk 1 from A to C\n" + with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout: + hanoi(3, 'A', 'B', 'C') + self.assertEqual(mock_stdout.getvalue(), expected_output) + + def test_hanoi_with_zero_disks(self): + with self.subTest(n=0, source='A', auxiliary='B', target='C'): + expected_output = "" + with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout: + hanoi(0, 'A', 'B', 'C') + self.assertEqual(mock_stdout.getvalue(), expected_output) + + def test_hanoi_with_negative_disks(self): + with self.subTest(n=-1, source='A', auxiliary='B', target='C'): + expected_output = "" + with unittest.mock.patch('sys.stdout', new=io.StringIO()) as mock_stdout: + hanoi(-1, 'A', 'B', 'C') + self.assertEqual(mock_stdout.getvalue(), expected_output) + +if __name__ == "__main__": + unittest.main()