title: Pytest with argparse: how to test user is prompted for confirmation?
body: <p>I have a CLI tool, and would like to test that the user is prompted to confirm a choice using <code>input()</code>. This would be equivalent as using <code>raw_input()</code> in Python 2.</p>
  
  <h3>Code</h3>
  
  <p>The (paraphrased) code to test looks like:</p>
  
  <pre><code>import sys
  import argparse
  
  
  def confirm():
      notification_str = "Please respond with 'y' or 'n'"
      while True:
          choice = input("Confirm [Y/n]?").lower()
          if choice in 'yes' or not choice:
              return True
          if choice in 'no':
              return False
          print(notification_str)
  
  
  def parse_args(args):
      parser = argparse.ArgumentParser()
      parser.add_argument('-d', '--destructive', action='store_true')
      return parser.parse_args()
  
  
  def main():
      args = parse_args(sys.argv[1:])
      if args.destructive:
          if not confirm():
              sys.exit()
      do_stuff(args)
  
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <h3>Question</h3>
  
  <p>I am using pytest as my framework. How do I make it so I can test that the confirmation prompt is showing up in the CLI? If I try to compare <code>stdout</code> I get the error: <code>OSError: reading from stdin while output is captured</code>.</p>
  
  <p>I want to make sure that:</p>
  
  <ol>
  <li>The confirmation shows up when the destructive flag is set</li>
  <li>It doesn't show up when it isn't</li>
  </ol>
  
  <p>I will be using the following code in another file:</p>
  
  <pre><code>import pytest
  from module_name import main
  
  
  def test_user_is_prompted_when_destructive_flag_is_set():
      sys.argv['', '-d']
      main()
      assert _  # What the hell goes here?
  
  
  def test_user_is_not_prompted_when_destructive_flag_not_set():
      sys.argv['',]
      main()
      assert _  # And here too?
  </code></pre>