Wednesday, 13 October 2021

Test if given input value does not break from while True loop

I want to unit test a function called prompt_process. The function's role is to prompt whether to call another function, process, or exit the program altogether, based on the return value of input:

process.py

import sys


def process():
    pass


def prompt_process():
    answer = input("Do you want to process? (y/n)").lower()
    while True:
        if answer == 'y':
            return process()
        elif answer == 'n':
            sys.exit(0)
        else:
            answer = input("Invalid answer - please type y or n").lower()

Testing the if/elif clauses is simple enough using mocks:

test_process.py

import unittest
from unittest import mock

import process


class TestProcess(unittest.TestCase):
    @mock.patch('process.process')
    def test_prompt_process_calls_process_if_input_is_y(self, mock_process):
        with mock.patch('process.input', return_value='y'):
            process.prompt_process()
        mock_process.assert_called_once()
        
    def test_prompt_process_exits_if_input_is_n(self):
        with mock.patch('process.input', return_value='n'):
            with self.assertRaises(SystemExit):
                process.prompt_process()


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

But I don't know how to test the else clause of the function. Ideally, it should test that the loop keeps running for input values other than y and n, but since I can't "mock" a while True loop I'm not sure how to proceed.

Is there any solution for testing this, or is this something I shouldn't bother with in the first place?



from Test if given input value does not break from while True loop

No comments:

Post a Comment