简体   繁体   中英

Unit testing with multi-step user inputs

I'm unit testing a part of code which asks for one argument at a time before bringing them back. I'd like to write a test that the prompt is what it should be, but I'm unsure how to test each stage of the prompt. Say the prompt is: "what is variable 1" --user input-- "what is variable 2" --user input--

Then the unit test would be something like..

with self.subTest(args=args):
                    result = _run(args)
                    self.assertRegex(result.stdout,r'(?m)^'what is variable 1?"

But when I try to submit just one variable at a time to 'args' then the test hangs. But when I try to submit all variables at once, the code fails and says "'what is variable 1' not found in ''"

First, you can not read from stdout like you did in your example. To be able to read from stdout from within your own code you would first have to ensure stdout is actually writing to some stream you can read from. The mechanism (for C, so you would have to port it to Python) is explained here: C language. Read from stdout .

Second, when doing unit-testing, you usually take a different approach. You would not check on stdout if the strings appeared (this would be done on higher testing levels like integration-testing or system-testing). Instead, during unit-testing you would isolate your code from the real interaction with the operating system. For example, if you use input , then you could mock the input function. See Mock user input() . The difference to your approach is then, that you don't look at stdout, but check instead if your code really called input in the correct way. Moreover, you can also make the mock return simulated user input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM