|
| 1 | +import unittest |
| 2 | +import subprocess |
| 3 | +import os |
| 4 | +import sys |
| 5 | + |
| 6 | +class TestArmstrongNumber(unittest.TestCase): |
| 7 | + def setUp(self): |
| 8 | + # Path to the Armstrong-Number.py script |
| 9 | + self.script_path = os.path.join("math", "Armstrong-Number", "Armstrong-Number.py") |
| 10 | + |
| 11 | + def run_script_with_input(self, user_input): |
| 12 | + # Run the script as a subprocess and provide input via stdin |
| 13 | + process = subprocess.Popen( |
| 14 | + [sys.executable, self.script_path], |
| 15 | + stdin=subprocess.PIPE, |
| 16 | + stdout=subprocess.PIPE, |
| 17 | + stderr=subprocess.PIPE, |
| 18 | + text=True |
| 19 | + ) |
| 20 | + stdout, stderr = process.communicate(input=user_input) |
| 21 | + return stdout, stderr |
| 22 | + |
| 23 | + def test_valid_armstrong_number(self): |
| 24 | + stdout, _ = self.run_script_with_input("153\n") |
| 25 | + self.assertIn("153 is an Armstrong Number!", stdout) |
| 26 | + |
| 27 | + def test_invalid_armstrong_number(self): |
| 28 | + stdout, _ = self.run_script_with_input("154\n") |
| 29 | + self.assertIn("154 is NOT an Armstrong Number.", stdout) |
| 30 | + |
| 31 | + def test_invalid_input_handling(self): |
| 32 | + # The script asks again if input is invalid, so we send invalid then valid |
| 33 | + stdout, _ = self.run_script_with_input("abc\n153\n") |
| 34 | + self.assertIn("That doesn't look like a valid number", stdout) |
| 35 | + self.assertIn("153 is an Armstrong Number!", stdout) |
| 36 | + |
| 37 | + def test_negative_input(self): |
| 38 | + stdout, _ = self.run_script_with_input("-5\n153\n") |
| 39 | + self.assertIn("Please enter a positive number!", stdout) |
| 40 | + |
| 41 | +if __name__ == "__main__": |
| 42 | + unittest.main() |
0 commit comments