Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Infinite loop testing

How could I test an infinite loop?
For example:

func.py

def func():
    while True:
        char = input().lower()
        if char == 'q':
            break 
        elif char.isalpha():
            print("It's not a number")
        if int(char) == #some_number
            break
        else:
            print('Try again')
        

test.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def test_func():
    ???

Is there any solution for testing this?

>Solution :

You can use unittest to mock the user’s input:

import builtins
from unittest.mock import patch

def func():
    while True:
        char = input().lower()
        if char == 'q':
            break 
        elif char.isalpha():
            print("It's not a number")
        if int(char) == 3:
            break
        else:
            print('Try again')

def test_func(inputs):
    with patch("builtins.input") as input_mock:
        input_mock.side_effect = inputs
        func()

test_func(["q"])
test_func(["3"])  
test_func(["4", "5", "6"])  # StopIteration error indicates this input is not sufficient for the function to return
test_func(["a", "b", "c", "q"])  # ValueError indicates a bug in the function
test_func(["4", "5", "6", "q"])  # Try again 3 times as expected
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading