0

Edit: I am flagging my own question as duplicate. My problem has a similar solution to this thread How to test a function with input call?.

I have a question regarding unit tests in python.

I have implemented the following function:

def prompt():
    while True:
        try:
            choice = input("What do you want to do? ")
        except EOFError:
            exit("Program Terminated.")
        except KeyboardInterrupt:
            exit("Program Terminated.")

        if choice in ['1', '2', '3', '4', '0']:
            return int(choice)

and to test it, I have:

def test_prompt():
    assert prompt() ...

My question is, how do I test my prompt() function with pytest? So far, I don't have problems with my other functions since their return value does not depend on the user input.

PS: If this question is duplicated, can you pls drop the link and I'll give it a go. Thank you.

Seven
  • 330
  • 2
  • 15
  • This one looks pretty similar: https://stackoverflow.com/a/36377194/786559 . You replace the `input()` function with another function that returns a known string (`Mark` in that example). Also see [this one](https://stackoverflow.com/a/59998012/786559) if you want to test a sequence of user inputs. – Ciprian Tomoiagă Jun 13 '22 at 15:45
  • @CiprianTomoiagă, okay, allow me to read it – Seven Jun 13 '22 at 15:47
  • Agreed, the `EOFError` is easily simulated if you provide an explicit file-like object as an argument. The `KeyboardInterrupt` is harder to simulate, because it's not related the file you read from, but to a signal received by your program. – chepner Jun 13 '22 at 15:50
  • Let me get back to you guys after I finish reading it. Thank you – Seven Jun 13 '22 at 15:52
  • Hi, I flagged my own question as duplicate. Thank you for helping me out – Seven Jun 13 '22 at 16:22

0 Answers0